/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.moxiu.browser;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Vector;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.Drawable;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ClientCertRequest;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.HttpAuthHandler;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebView.PictureListener;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.cmcm.newssdk.entity.Article;
import com.cmcm.newssdk.impl.NewsSdkReportImpl;
import com.cmcm.newssdk.report.ReportListPageTime;
import com.cmcm.newssdk.report.ReportReadTime;
import com.greengold.ggexposure.AdLoadListener;
import com.greengold.ggexposure.NativeAdFactory;
import com.greengold.ggexposure.ad.AdConfig;
import com.greengold.ggexposure.frame.AdBaseBean;
import com.moxiu.browser.TabControl.OnThumbnailUpdatedListener;
import com.moxiu.browser.UrlBarAutoShowManager.TargetOnShowListener;
import com.moxiu.browser.homepage.HomePagePara;
import com.moxiu.browser.homepages.HomeProvider;
import com.moxiu.browser.mainactivity.B_BrowserMainManager;
import com.moxiu.browser.mainactivity.GDTwebviewJavaScriptBrowser;
import com.moxiu.browser.preferences.BrowserJsInject;
import com.moxiu.browser.util.BrowserAdblock;
import com.moxiu.browser.util.BrowserAdblockImpl;
import com.moxiu.browser.util.Common;
import com.moxiu.browser.util.InnerJumpToBrowserUtil;
import com.moxiu.launcher.R;
import com.moxiu.launcher.config.AdCons;
import com.moxiu.launcher.config.BDStatistic;
import com.moxiu.launcher.config.StaticConfig;
import com.moxiu.launcher.config.StaticMethod;
import com.qq.e.ads.cfg.MultiProcessFlag;
import com.qq.e.ads.nativ.NativeAD;
import com.qq.e.ads.nativ.NativeAD.NativeAdListener;
import com.qq.e.ads.nativ.NativeADDataRef;
import com.vbooster.booster.MainActivity;

/**
 * Class for maintaining Tabs with a main WebView and a subwindow.
 */
public class Tab implements PictureListener, TargetOnShowListener {

	private static String cccc = "!function(){function o(o){}function r(){clearTimeout(i),d.parentNode&&d.parentNode.removeChild(d)}function e(){function o(){if(s&&!(c()-r>1e4)){var e=window.document,a=e.body||e.documentElement;a&&!a.contains(d)&&a.appendChild(d),i=setTimeout(o,100)}}clearTimeout(i);var r=c();o()}function a(o){\"boolean\"==typeof o&&(s=o),s?e():r()}function n(){for(var r=[/^http:\\/\\/game\\.cmcm\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?tmall\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?jd\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?suning\\.com\\//,/^http?:\\/\\/(?:[^\\/]+\\.)?iqiyi\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?u17\\.com\\//,/^https?:\\/\\/12306\\.m\\.liebao\\.cn\\//,/^http:\\/\\/cb\\.ksmobile\\.com\\//,/game[\\.\\-]361yun/,/\\.liebao\\.cn\\/game\\/[^\\/]+\\//,/^https?:\\/\\/www\\.google(?:\\.[a-z]+){1,3}\\/maps\\//,/^http:\\/\\/map\\.baidu\\.com\\//],e=r.length-1;e>-1;--e)if(r[e].test(location.href))return void o(\"夜间模式黑名单\");a();var n,t='html,body,h2,h3,h4,h5,h6,table,tr,td,th,tbody,form,ul,ol,li,dl,dd,section,footer,nav,strong,aside,header,label,font,hr{background-color:##bg;color:##text;border-color:##border;box-shadow:0 0 0;text-shadow:0 0 0;}html body{background-color:##bg;}article,dt,div,h1{background-color:##bg;color:##text;border-color:##border;box-shadow:none;text-shadow:none;}p{color:##text;border-color:##border;box-shadow:0 0 0;text-shadow:0 0 0;}div[id=\"x-video-button\"],div[class=\"x-advert\"]{background-color:transparent;}span,em{background-color:transparent;color:##text;border-color:##border;box-shadow:0 0 0;text-shadow:0 0 0;}html input,html select,html button,html textarea{box-shadow:0 0 0;color:##text;background-color:##bg;border-color:##border;}html input:focus,html select:focus,html option:focus,html button:focus,html textarea:focus{background-color:##bg;color:##text;border-color:##borderFocus;outline:2px solid ##borderFocus;}html input:hover,html select:hover,html option:hover,html button:hover,html textarea:hover{background-color:##bg;color:##text;border-color:##borderFocus;outline:2px solid ##borderFocus;}html input[type=text],html input[type=password]{background-image:none;}html input[type=submit],html button{opacity:.5;outline:1px solid ##border;}html input[type=submit]:hover,html button:hover{opacity:1;outline:1px solid ##borderFocus;}html img[src],html input[type=image]{__opacity:.5}html input[type=image]:hover{opacity:1;}div[class=\"img-view\"],ul[id=\"imgview\"],a[class^=\"prev\"],a[class^=\"next\"]a[class^=\"topic_img\"],a[class^=\"arrow\"],a:active[class^=\"arrow\"],a:visited[class^=\"arrow\"],img[src^=\"data\"],img[loaded=\"1\"]{background:none;}a[class^=\"arrow\"]{height:0;}.anythingSlider .arrow{background:none;}html a,html a *{background-color:transparent;color:##link;text-decoration:none;border-color:##border;text-shadow:0 0 0;}html a:visited,html a:visited *{color:##linkVisited;}html a:hover,html a:active{color:none;border-color:transparent;}#toolbarBox,#move_tip{background:none;}#logolink,#mask{background-color:##bg;border-bottom:none;}*:before,*:after{color:##text;border-color:##border;}input::-webkit-input-placeholder{color:##text;}div[class=\"x-prompt\"],div[class=\"x-dashboard\"]{background:none;}div[class=\"x-progress-play-mini\"]{background:#eb3c10;}div[class=\"x-console\"],div[class=\"x-progress\"],div[class=\"x-progress-seek\"]{background:none;}div[class=\"x-progress-track\"]{background-color:#555555;}div[class=\"x-progress-load\"]{background-color:#909090;}div[class=\"x-progress-play\"],div[class=\"x-seek-handle\"]{background-color:#eb3c10;}iframe{opacity:0.7;}',c=[{host:/^[^.]+\\.google(?:\\.[a-z]+){1,3}$/,append:'.msfi{border-color:##border;background-color:##bg;}#gbr,.gbgs4{background:none;}.sbico{background-color:transparent;}#gbg{background-color:##border;}#views,#views *{background-color:transparent;}#og_head{opacity:0.7;}#og_head>*{background:none;}#og_head,#og_head *{background-color:transparent;}#nav{background:##border;}#nav *,#nav *:before{background-color:transparent;}#cv__cntbb{background:##border;}#signIn{color:#fff;}span.spell{color:##text;}[role=\"button\"] *{color:#000;}html button{background:##border;}#views .Rn{background:##border;}#views .Rn *{color:##text;}.jhp input[type=\"submit\"], .sbdd_a input{background:##border;}html .vk_bk{color:##text;}'},{host:/^[^.]+\\.facebook\\.com$/,append:'button[type=\"submit\"] span{color:##bg;}#cover-name-root,#cover-name-root *,#mJewelNav{background-color:transparent;}.img{opacity:0.7}#header{background:##border;}#header *:not(.flyout):not(.flyout *){background-color:transparent;}article,dt,div,h1{background-color:transparent;}._5c0e{background-color:##border;}.touch ._56bt,.touch ._5c9u,.touch ._5ca9,.touch button._5c9u{background:##border;}.touch ._56bt *,.touch ._5c9u *,.touch ._5ca9 *,.touch button._5c9u *{color:#ccc;}.mSearchOverlay,.mSideArea{background-color:##bg;}.flyout,#MMegaphone.MPagesManagerPromoStory{background:##border;}.mFuturePageHeader button[type=\"submit\"] span{color:##text;}html .fill{background:##borderFocus;}.chatHighlight{-webkit-animation:none;}[data-sigil=\"marea\"]{background:##border;}'},{host:/^[^.]+\\.youtube\\.com$/,append:'html button{border:none;}#guide-overlay{background-color:rgba(0,0,0,0.3);}#player,#player *{background-color:transparent;}._mih,._mgh{background:none;}article,dt,div,h1,._mlc,._mlc *{background-color:transparent;}._mmx a>span{background-color:#1b7fcc;color:#ccc;}video{display:inline-block;}._mik,._mzm,._mjk,._mdm,._mpv,._mam,._mjk ._mfk,._mdm ._macb,._msv,._mbv,._mcv{background:##bg;}iframe{opacity:1;}._mwp{background:##bg;}#content>div:first-child>div:first-child>div:first-child>div:first-child{background:##border;}#content [onclick^=\"return clk(this)\"]{background:##bg;}[aria-role=\"alertdialog\"]{background:##bg;}[onclick^=\"return koya.onEvent(arguments[0]||window.event,\"][style^=\"width:33.3\"],[aria-label=\"More options\"]{background:##border;}'},{host:/^[^.]+\\.yahoo\\.com$/,append:\".gradient,.gradient *,.yucs-logo,.yucs-logo *{background-color:transparent;}.yom-overlay,.yom-overlay *{background-color:transparent;}\"},{host:/.yandex\\.ru$/,append:'html .b-logo{background-color:#999;}.b-form-input{outline:1px solid ##border;}.b-head-search__bottom:after{border:none;}.b-region,.b-widget,html .b-text-button,.b-link{background:##border;}.b-icon-button,[class^=\"b-slider-arrows\"]{opacity:0.7;}'},{host:/^[^.]+\\.ebay\\.[^.]+$/,append:\"html body,.middle>.main>.top{background:##bg;}.inputStyle{border-color:##border;}.btnWdth{opacity:0.7;}.homeV2parent{background:none;}#cvr{background-color:rgba(0,0,0,0.5);}\"},{host:/^[^.]+\\.globo\\.com$/,append:\"#bloco-principal .destaque.principal:before, #bloco-principal .destaque.secundario:before, .mobile-grid-full:before, .first-scroll-container .destaque.duplo .esquerda:before, .first-scroll-container .destaque.duplo .direita:before, .first-scroll-container .destaque-wide-triplo-foto-topo.destaque .chamada>li:before, .first-scroll-container .destaque-wide-triplo-foto-topo.destaque .chamada>li:nth-child(2):before, .agrupador-sextuplo .destaques li:before, .agrupador-musica-triplo .destaques li:before, .agrupador-sextuplo .destaques li:first-child:before, .agrupador-musica-triplo .destaques li:first-child:before, .agrupador-musica-triplo .top-container .foto:before, .box-complementar-uber li:before, .widget .box-widgets-personalizaveis.analytics-area .widget-highlights .area-topo:before,.topglobocom .topglobocom3 .mais-vistas .entretenimento li:before, .topglobocom .topglobocom3 .mais-vistas .esportes li:before, .topglobocom .topglobocom3 .mais-vistas .noticias li:before{background:##border;border-color:##border;}header,.link-see-more,.mobile-grid-full,.topglobocom .topglobocom3 .mais-vistas .entretenimento li, .topglobocom .topglobocom3 .mais-vistas .esportes li, .topglobocom .topglobocom3 .mais-vistas .noticias li{background:##bg;}\"},{host:/^([^.]+\\.)?mail\\.ru$/,append:'*:after{background-color:##border;}.block{box-shadow:0 2px 0 ##border;}.weather:before,.w-tabs:before,.w-tabs:after{background:none;}[class*=\"image\"]{opacity:0.7;}'},{host:/^[^.]+\\.liebao\\.cn$/,append:\"h2,div,strong{background-color:transparent;}.android-btn,.iphone-btn{opacity:0.7;}.game-item-play{background-color:##borderFocus;}\"},{host:/^[^.]+\\.cmcm\\.com$/,append:\".bg{background:none;}h2,h4,div,strong{background-color:transparent;}.active{outline:3px solid ##border;}.game-item-play{background-color:##borderFocus;}\"},{host:/^ssdk\\.adkmob\\.com$/,append:\".btn-dl{background-color:##border;box-shadow:0 2px 1px ##borderFocus;}.app-name:after{background:none;}\"},{host:/\\.twitter\\.com$/,append:\".content, .content *{background-color:transparent;}views,view,content{background-color:##bg;}#brand_bar{background-color:#50a7e6;}#brand_bar *{background-color:transparent;}\"},{host:/(?:\\.|^)web\\.de$/,append:\".teaser-wrapper,.teaser-wrapper *{background:none;}\"},{host:/\\.ruten\\.com\\.tw$/,append:\".page-header .main-menu ul.list li,.page-header .main-menu ul.list li span,.adver-text1,.clss-promo ul li:not(.cp-pchomepay){background:##border;}.clss-promo ul li *{background-color:transparent;}.cp-pchomepay,.clss-promo h2{opacity:0.7}.title,.title span,.hide{background:##border;}.view{background:##borderFocus;}.adver-list{background-color:transparent;}.top-sellers li,.catalogue li h3{background:none;}\"},{host:/(?:\\.|^)ask\\.fm/,append:\"html{background:##bg;}.signupButton{background:##border;box-shadow:none;}#menu,#whosHere-label,#shareLinkReminder{background:##border;}#menu *,#shareLinkReminder *{background-color:transparent;border-color:##borderFocus;}\"},{host:/\\.milanuncios\\.com$/,append:\".cabbg,.x1,.buscanuncios{background:none;}.dimg,.logo,.f1{opacity:0.7}\"},{host:/\\.naver\\.com$/,append:\".ham,img,.imsv{opacity:0.7;background-color:transparent;}.sch_w,.sch_inpw_in,.sch_inpw_in:before,.sch_inpw_in:after{background:##borderFocus;}.im,.imh,.sprh,.sp_rtk,.spuio,.imwt,.imw,.sc_psn .sc_psn_stt .sc_psn_a:before,.imhid,.id_hidden .sbl .sb_btns{color:transparent;opacity:0.7;}.dmm{background:rgba(0,0,0,0.5);}header span,header em{color:transparent;}html header{background-color:#3f63bf;opacity:0.7;}html header *{background-color:transparent;}.sc_cmt_wrp .sc_btn,.sc_err_wrp .sc_btn{box-shadow:none;}#video_area,#video_area *{background-color:transparent;}footer,footer *{background-color:transparent;}.home_poll .poll_lst li a,footer a{background-image:none;}.uio_link .ul_item:before,.uio_link .ul_item:after{background-color:##border;}\"},{host:/\\.dcinside\\.com$/,append:\".m_logo{background:none;}.issue_day,.btn_off,.img_comm,.box_rebtn .recomm{opacity:0.7;}.main_menu ul li{background:none;}.ng_icon a,.btn_extend,.btn_more,.btn_delete{background:##borderFocus;box-shadow:none;}.arr_tab_b,.arr_tab{display:none;}.m_search,.ng_box{background:##border;}.btn{background:##border;color:##text;}\"},{host:/\\.cnn\\.com$/,append:\"#smartbanner{background:none;}#smartbanner .sb-button{background:##border;box-shadow:none;}#smartbanner .sb-icon{opacity:0.7;}.section_header,.section_header_lower,.module_bgroup .cathd{background:##border;}.pagenav{opacity:0.7;}\"},{host:/(?:\\.|^)as\\.com$/,append:\".cnt-media-msg,.cnt-media-msg *,.hdr-in-nav,.publi_apuesta_iframe_2,.ntc-apoyos *{background:none;}.ntc-media-msg{background:rgba(0,0,0,0.5);}.res-p-marcador.finalizado,.res-p, .res-p-doble,.banner_sup:before,.banner_sup:after,.hdr-p,.btn-clasificacion,.modulo_escudos,.hdr-in-secondary,.hdr-buscador,.hdr-buscador-buscar2,.hdr-in-buscar,.hdr-secondary-aux,.hdr-in-nav:before,.tit-module-external,.tit-module-external:before,.ntc-apoyos,.tit-opi,.tit-module-internal:before,.ntc-opinion, .ntc-apoyo,.mdl-video-portadilla-black,.tit-module-media, .tit-module-gris-oscuro,.tit-module-media:before, .tit-module-gris-oscuro:before,.hdr-carrusel,.mdl-inf-header div,.tit-module-elpais,h3,.ftr_inf{background:##border;}.btn-clasificacion:before{box-shadow:none;}.activo{background:##borderFocus;}.hdr-in-secondary *,.hdr-p *,.s-left{background-color:transparent;}.tabs-opn{opacity:0.7}\"},{host:/\\.amazon\\.\\w+$/,append:\"#nav-backtotop,.a-button-inner,.a-button,.a-expander-header,.nav-a{background:##border;box-shadow:none;}#nav-logobar,.a-global-nav-wrapper{background:##bg;}.a-global-nav-wrapper *,#nav-logobar *{background-color:transparent;}#customerReviewsSmallStars,.a-icon{opacity:0.7;}.nav-search-submit .nav-input,html input.a-button-input[type=submit]{opacity:0.01;}.a-color-alternate-background{background:transparent;}\"},{host:/(?:\\.|^)searchmobileonline\\.com$/,append:\".top_nav_tab{background:##border;}.app-row{background:##border;}.app-row *{background-color:transparent;}\"},{host:/\\.baidu\\.com$/,append:\".se-bn *,#index-bn,#index-bn *{color:#000;}.se-input,.se-encode{background:##border;}.xs-image img{opacity:1;}.form-item{background-color:##border;}.plus-edit ul{background-color:##border;}#index-modal{background-color: rgba(9,9,9,.3);}#search-card .cur,.h-tab .cur{background:##border;}.imglist li,.hotlist li,.searchbox,.searchbox *,.searchbox input:hover{background-color:##border;}.searchbox .searchbox-btn{background:##link;color:#fff;}.baiduapp-icon{background-color: transparent;}.baiduapp-icon:before{border-top-color: #717077;}.callicon-wrap{background-color: transparent;}#admin-view .slide{background: #c7c7c7;}#admin-view .slide.on{background: #1bc059;}\"},{host:/(?:\\.|^)aliexpress\\.com$/,append:\".ui-button-normal,.ui-button-normal:link,.ui-button-normal:active,.ui-button-third{background:##border;}header{background:##bg;}\"},{host:/(?:\\.|^)blic\\.rs$/,append:\".button2,.button2_off{background:##border;color:##text;box-shadow:none;}\"},{host:/(?:\\.|^)omegle\\.com$/,append:\".youmsggroup .msggroup-msg{background:##border;}.strangermsggroup .msggroup-msg{background:##borderFocus;}\"},{host:/(?:\\.|^)varzesh3\\.com$/,append:\"font{color:##text;}\"},{host:/^v\\.m\\.liebao\\.cn$/,css:function(){return t.replace(/html a(?::[a-z]+)?(?: \\*)?/gi,\"$&:not(.btn)\")+\".detail_cover img,.banner_wrap img,img.cover_img{opacity:1;}#nav .news_all a:before{box-shadow:none;}.trans_layer,.page_layer{background-color:rgba(0,0,0,.3);}.list_condition a.cur{background:##borderFocus;}.right_side{background-color:transparent;}.update_tip{background:##borderFocus;}.update_tip:after{border-color:##borderFocus;}.search_latest li a,.search_hot li a,.form_search,.search_mask{background-color:##border;}.ico_filter{color:##text;}#nav a.cur{border-color: #527899;}#nav.news_nav a.cur span{border-color: #527899;}\"}},{host:/^m\\.58\\.com$/,append:'.city_box h4 p{background-color:transparent;}iframe[src^=\"http://static.track.58.com/\"]{background-color:##text;}.pc_banner img{z-index:0;}'},{host:/^m\\.freexs\\.cn$/,append:\".tfanye,.bfanye{background-color:transparent;}\"},{host:/^m\\.che168\\.com$/,append:\".topback-layer{background-color:transparent;}\"},{host:/(?:\\.|^)m\\.duba\\.com$/,append:\".site_logos li a.active{background:none;}.joke-cai,.joke-ding{background:none;}.imgbox i,.meitu-list ul li em{background-color:rgba(0,0,0,.7);}.btn_list li:first-child a,.links li a:first-child{color:#fff;}.meitu-nav ul li.on a,.novel-tab ul li.on{background:##border;}\"},{host:/waimai\\.baidu\\.com$/,append:\"#position-widget-city,#position-widget-city *,.history-title{background-color:transparent;}\"},{host:/mobile\\.baidu\\.com$/,append:\"app-card{background-color:transparent;border-color:##border;}.text-card .desc-more, .inapp-content .desc-more{background:-webkit-linear-gradient(left,rgba(0,0,0,.8),##border 20%);}.search-placeholder{background-color: #2D2C2B;}\"},{host:/image\\.baidu\\.com$/,append:\".searchbox,.searchbox form.fm,.searchbox .searchbox-wrap .searchbox-inline .searchbox-input input,.searchbox .searchbox-wrap .searchbox-inline .searchbox-input input:focus{background-color:##border;}.searchbox .searchbox-btn{background-image:none;}\"},{host:/baike\\.baidu\\.com$/,css:function(){return t.replace(/div/gi,\"$&:not(.toolbar-container)\")+\"html .toolbar-container *,p{background-color:transparent;}.search-button{background:##border;color:##text;}\"}},{host:/^m\\.zongheng\\.com$/,append:\".navigator>:nth-child(-n+2){background:##border;}.menu{background:none;}\"},{host:/^m\\.jiayuan\\.com$/,append:\".login_bg div{background-color: transparent;}.login_bg{background:none; background-color:##bg;}.login_btn{background-color: ##border; box-shadow: 0px 1px 1px #5C5C5C;}.login_list a{background-color:##border;}\"},{host:/(?:\\.|^)17k\\.com$/,css:function(){return t.replace(/label/g,\"_label\")+\".Menu{background:none;}\"}},{host:/(?:\\.|^)sohu\\.com$/,append:\".player_controls,.player_controls *,.video_title,.video_title *,.player .gg_area{background-color:transparent;}header .head{background:##border;}\"},{host:/(?:\\.|^)youku\\.com$/,append:\".x-player,.x-player *{background-color:transparent;}.v *,.p *{background-color:transparent;}.x-player .x-video-info .x-mask{background: #000;}\"},{host:/(?:\\.|^)v\\.qq\\.com$/,css:function(){return t.replace(/div|span/g,'$&:not([class^=\"tvp_\"])')}},{host:/(?:\\.|^)tudou\\.com$/,append:\".play-view,.play-view *{background-color:transparent;}\"},{host:/(?:\\.|^)iqiyi\\.com$/,append:\".mod-news,.mod-news:after{background:none;}.mod-news *{background:##border;}\"},{host:/(?:\\.|^)ganji\\.com$/,append:\".thumb-img-indexs,.zhiweichengnuo{background:none;}.feedback-links{background:##border;}.im-msg{background:none;}\"},{host:/(?:\\.|^)sina\\.cn$/,append:\".news_list .news_list_img img,.swipe_pic img,.carditems_list_dt img{opacity:1;}\"},{host:/^m\\.anjuke\\.com$/,append:\".imgblock .pintro,#pnav{background-color: transparent;}.imgblock .pintro .pinfo{background-color: rgba(0,0,0,0.6);}.imgblock .pnav li{  background: #c4c4c4;}.imgblock .pnav .focus{background: #62ab00;}.subblock .tgop, .subblock .natop{background: #e54c00;}.subblock .kftop, .subblock .ykop{  background: #51a308;}.I .m2{background:none;}.Gs2{background-image: -webkit-gradient(linear,0 0,0 100%,from(#525252),to(#0D0D0D));}.Gs2 a{color: #a8ecff;}.spTab{background-image:none;}.spTab .active{border-color:#969698;}.sx,.I .m2 label, .I .d1 label{background-image:none;}.m2 label span, .d1 label span{background-color:#97a3ad;}.sxr .tapping{color: #333;}.fangdongNum{background-image:none;}.b1 .active, .b1 .active1,.mainmenu .active{background-color:#151413;}.b1 .active,.mainmenu .active{color:#fff;}\"},{host:/^m\\.mh\\.9724\\.com$/,append:\".btn_blue{background:##border;} .btn_bubble{background: rgba(54,60,66,.92);}.show_more{background: -webkit-linear-gradient(left,rgba(250,247,245,0) 0,rgba(0, 0, 0, 1) 20%,rgba(21, 20, 19, 1) 100%);}.show_more:after{border-color:#00c8ff;}\"},{host:/^m\\.ly\\.com$/,append:\"#commonUpLayer{background: rgba(0,0,0,.7);}.pic_mask h3{background-color: transparent;}.ticket dt,.scenery-neary,.ticket dt{background:none;}.pic_mask{background: linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));background: -moz-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));background: -webkit-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));background: -o-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));background: -ms-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));}.detail_nav li .activate span{border-color:#6D8193;}.header-menu-btn:before, .header-menu-btn i, .header-menu-btn:after{background: #00c8ff;}.page-back:before{border-color:#00c8ff;}.pbngdda-nsnwbwl,.pbngdda-nsnwbwl p{background: #636363;}.pbngdda-nsnwbwl div p:last-child{margin-top:0; padding-top:1px;}.content{background:none;}.content p{background-color: transparent;}\"},{host:/^passport\\.ly\\.com$/,append:\".inputcontent p,.inputcontent input,.inputcontent input:hover,.inputcontent input:focus{background:##border;}.inputcontent p:first-child i,.inputcontent p:nth-child(2) i{background-color:##border;}.btn-blue{background-color:##border;}\"},{host:/^m\\.xxsy\\.net$/,append:\".tab li.animbg{border-bottom: 3px solid ##border;}.tab > ul,.tab > ul > li{background-color: transparent;}\"},{host:/m\\.yiche\\.com$/,append:\".m-focus-box .pagination-focus{background-color:transparent;}.m-focus-box .swiper-pagination-switch{background: #9DA2A3;}.m-focus-box .swiper-active-switch{background: #C00;}.m-focus-box a.arrow-left, .m-focus-box a.arrow-right{height:60px;}.video-play-box > div,#x-player > div:not(.x-dashboard){background-color: transparent;}.x-mask{background: #000;}\"},{host:/m\\.tiexue\\.net$/,append:\".swipe .wrap span{background-color: rgba(0, 0, 0, 0.4);}#position li,#position span,#position span em,#position{background-color: transparent;}#jujiaoTab a{  background: #c6c6c6;}#jujiaoTab .on{background: #c5020d;}\"},{host:/m\\.xinjunshi\\.com$/,append:\".navitems,.swiper .pagination,.footer,ul.navitems_f{background:none;}.swiper .swiper-pagination-switch{background: #a9a89d;  border: 1px solid rgba(0,0,0,0.6);}.swiper .swiper-active-switch{  border: 1px solid #43e2fd;background: #58d8ff;}.r-paging-button{background:##border;}\"},{host:/budejie\\.com$/,append:\"#post-tab .active{background-color:##border;}\"},{host:/(?:\\.|^)ifeng\\.com$/,css:function(){return t.replace(/opacity/g,\"__opacity\")+\".module_title{background:##border;}\"}},{host:/^m\\.kuaidi100\\.com$/,append:\"nav{background:##border;}\"}];if(location.hostname)for(var e=c.length-1;e>-1;--e){var b=c[e],i=b.host,s=!1;if(i?i.test(location.hostname)&&(s=!0):b.reg.test(location.href)&&(s=!0),s){var l=b.css;n=\"string\"==typeof l?l:\"function\"==typeof l?l():t+b.append;break}}else n=t.replace(/outline/g,\"__outline\").replace(/:after/,\":not(.i-video i):after\")+\".box-border-wap{background-color:transparent;}.list_main font{color:#fff9e8;}.news-hotword a{background: ##border;}\";\"string\"!=typeof n&&(n=t);var u={bg:\"#111317\",text:\"#6b7d96\",font:\"#cc0000\",link:\"#6ea9c4\",linkVisited:\"#598ba0\",border:\"#354255\",borderFocus:\"#587885\"};d.href=\"data:text/css,\"+n.replace(/;/g,\"!important;\").replace(/##([a-z]+)/gi,function(o,r){return u.hasOwnProperty(r)?u[r]:o}),o(\"夜间模式样式生成完毕\")}function t(){!l&&document.documentElement&&(l=!0,clearInterval(i),document.removeEventListener(\"readystatechange\",t,!1),document.removeEventListener(\"DOMContentLoaded\",t,!1),window.removeEventListener(\"load\",t,!1),o(\"夜间模式样式异步初始化\"),n())}if(!window.__lb_nightModeJSInjected){window.__lb_nightModeJSInjected=!0;var c;c=\"undefined\"!=typeof performance&&performance.now?function(){return performance.now()}:function(){return Date.now()};o(\"夜间模式运行\");var d=document.createElement(\"link\");d.rel=\"stylesheet\";var b=\"lb_night_style\";d.id=b;var i,s=!0;if(__lb_night_call=function(r){o(\"夜间模式切换|\"+r),\"switch_day\"===r?a(!1):\"switch_night\"===r&&a(!0)},document.documentElement)o(\"夜间模式样式同步初始化\"),n();else{var l=!1,i=setInterval(t,16);document.addEventListener(\"readystatechange\",t,!1),document.addEventListener(\"DOMContentLoaded\",t,!1),window.addEventListener(\"load\",t,!1)}}}();";
	// private static String cccc=
	// "!function(){function o(o){}function r(){clearTimeout(i),d.parentNode&&d.parentNode.removeChild(d)}function e(){function o(){if(s&&!(c()-r>1e4)){var e=window.document,a=e.body||e.documentElement;a&&!a.contains(d)&&a.appendChild(d),i=setTimeout(o,100)}}clearTimeout(i);var r=c();o()}function a(o){\"boolean\"==typeof o&&(s=o),s?e():r()}function n(){for(var r=[/^http:\\/\\/game\\.cmcm\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?taobao\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?tmall\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?jd\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?suning\\.com\\//,/^https?:\\/\\/(?:[^\\/]+\\.)?u17\\.com\\//,/^https?:\\/\\/12306\\.m\\.liebao\\.cn\\//,/^http:\\/\\/cb\\.ksmobile\\.com\\//,/game[\\.\\-]361yun/,/\\.liebao\\.cn\\/game\\/[^\\/]+\\//,/^https?:\\/\\/www\\.google(?:\\.[a-z]+){1,3}\\/maps\\//,/^http:\\/\\/map\\.baidu\\.com\\//],e=r.length-1;e>-1;--e)if(r[e].test(location.href))return void o(\"夜间模式黑名单\");a();var n,t='html,body,h2,h3,h4,h5,h6,table,tr,td,th,tbody,form,ul,ol,li,dl,dd,section,footer,nav,strong,aside,header,label,hr{background-color:##bg;color:##text;border-color:##border;box-shadow:0 0 0;text-shadow:0 0 0;}html body{background-color:##bg;}article,dt,div,h1{background-color:##bg;color:##text;border-color:##border;box-shadow:none;text-shadow:none;}p{color:##text;border-color:##border;box-shadow:0 0 0;text-shadow:0 0 0;}div[id=\"x-video-button\"],div[class=\"x-advert\"]{background-color:transparent;}span,em{background-color:transparent;color:##text;border-color:##border;box-shadow:0 0 0;text-shadow:0 0 0;}html input,html select,html button,html textarea{box-shadow:0 0 0;color:##text;background-color:##bg;border-color:##border;}html input:focus,html select:focus,html option:focus,html button:focus,html textarea:focus{background-color:##bg;color:##text;border-color:##borderFocus;outline:2px solid ##borderFocus;}html input:hover,html select:hover,html option:hover,html button:hover,html textarea:hover{background-color:##bg;color:##text;border-color:##borderFocus;outline:2px solid ##borderFocus;}html input[type=text],html input[type=password]{background-image:none;}html input[type=submit],html button{opacity:.5;outline:1px solid ##border;}html input[type=submit]:hover,html button:hover{opacity:1;outline:1px solid ##borderFocus;}html img[src],html input[type=image]{__opacity:.5}html input[type=image]:hover{opacity:1;}div[class=\"img-view\"],ul[id=\"imgview\"],a[class^=\"prev\"],a[class^=\"next\"]a[class^=\"topic_img\"],a[class^=\"arrow\"],a:active[class^=\"arrow\"],a:visited[class^=\"arrow\"],img[src^=\"data\"],img[loaded=\"1\"]{background:none;}a[class^=\"arrow\"]{height:0;}.anythingSlider .arrow{background:none;}html a,html a *{background-color:transparent;color:##link;text-decoration:none;border-color:##border;text-shadow:0 0 0;}html a:visited,html a:visited *{color:##linkVisited;}html a:hover,html a:active{color:none;border-color:transparent;}#toolbarBox,#move_tip{background:none;}#logolink,#mask{background-color:##bg;border-bottom:none;}*:before,*:after{color:##text;border-color:##border;}input::-webkit-input-placeholder{color:##text;}div[class=\"x-prompt\"],div[class=\"x-dashboard\"]{background:none;}div[class=\"x-progress-play-mini\"]{background:#eb3c10;}div[class=\"x-console\"],div[class=\"x-progress\"],div[class=\"x-progress-seek\"]{background:none;}div[class=\"x-progress-track\"]{background-color:#555555;}div[class=\"x-progress-load\"]{background-color:#909090;}div[class=\"x-progress-play\"],div[class=\"x-seek-handle\"]{background-color:#eb3c10;}iframe{opacity:0.7;}',c=[{host:/^[^.]+\\.google(?:\\.[a-z]+){1,3}$/,append:'.msfi{border-color:##border;background-color:##bg;}#gbr,.gbgs4{background:none;}.sbico{background-color:transparent;}#gbg{background-color:##border;}#views,#views *{background-color:transparent;}#og_head{opacity:0.7;}#og_head>*{background:none;}#og_head,#og_head *{background-color:transparent;}#nav{background:##border;}#nav *,#nav *:before{background-color:transparent;}#cv__cntbb{background:##border;}#signIn{color:#fff;}span.spell{color:##text;}[role=\"button\"] *{color:#000;}html button{background:##border;}#views .Rn{background:##border;}#views .Rn *{color:##text;}.jhp input[type=\"submit\"], .sbdd_a input{background:##border;}html .vk_bk{color:##text;}'},{host:/^[^.]+\\.facebook\\.com$/,append:'button[type=\"submit\"] span{color:##bg;}#cover-name-root,#cover-name-root *,#mJewelNav{background-color:transparent;}.img{opacity:0.7}#header{background:##border;}#header *:not(.flyout):not(.flyout *){background-color:transparent;}article,dt,div,h1{background-color:transparent;}._5c0e{background-color:##border;}.touch ._56bt,.touch ._5c9u,.touch ._5ca9,.touch button._5c9u{background:##border;}.touch ._56bt *,.touch ._5c9u *,.touch ._5ca9 *,.touch button._5c9u *{color:#ccc;}.mSearchOverlay,.mSideArea{background-color:##bg;}.flyout,#MMegaphone.MPagesManagerPromoStory{background:##border;}.mFuturePageHeader button[type=\"submit\"] span{color:##text;}html .fill{background:##borderFocus;}.chatHighlight{-webkit-animation:none;}[data-sigil=\"marea\"]{background:##border;}'},{host:/^[^.]+\\.youtube\\.com$/,append:'html button{border:none;}#guide-overlay{background-color:rgba(0,0,0,0.3);}#player,#player *{background-color:transparent;}._mih,._mgh{background:none;}article,dt,div,h1,._mlc,._mlc *{background-color:transparent;}._mmx a>span{background-color:#1b7fcc;color:#ccc;}video{display:inline-block;}._mik,._mzm,._mjk,._mdm,._mpv,._mam,._mjk ._mfk,._mdm ._macb,._msv,._mbv,._mcv{background:##bg;}iframe{opacity:1;}._mwp{background:##bg;}#content>div:first-child>div:first-child>div:first-child>div:first-child{background:##border;}#content [onclick^=\"return clk(this)\"]{background:##bg;}[aria-role=\"alertdialog\"]{background:##bg;}[onclick^=\"return koya.onEvent(arguments[0]||window.event,\"][style^=\"width:33.3\"],[aria-label=\"More options\"]{background:##border;}'},{host:/^[^.]+\\.yahoo\\.com$/,append:\".gradient,.gradient *,.yucs-logo,.yucs-logo *{background-color:transparent;}.yom-overlay,.yom-overlay *{background-color:transparent;}\"},{host:/.yandex\\.ru$/,append:'html .b-logo{background-color:#999;}.b-form-input{outline:1px solid ##border;}.b-head-search__bottom:after{border:none;}.b-region,.b-widget,html .b-text-button,.b-link{background:##border;}.b-icon-button,[class^=\"b-slider-arrows\"]{opacity:0.7;}'},{host:/^[^.]+\\.ebay\\.[^.]+$/,append:\"html body,.middle>.main>.top{background:##bg;}.inputStyle{border-color:##border;}.btnWdth{opacity:0.7;}.homeV2parent{background:none;}#cvr{background-color:rgba(0,0,0,0.5);}\"},{host:/^[^.]+\\.globo\\.com$/,append:\"#bloco-principal .destaque.principal:before, #bloco-principal .destaque.secundario:before, .mobile-grid-full:before, .first-scroll-container .destaque.duplo .esquerda:before, .first-scroll-container .destaque.duplo .direita:before, .first-scroll-container .destaque-wide-triplo-foto-topo.destaque .chamada>li:before, .first-scroll-container .destaque-wide-triplo-foto-topo.destaque .chamada>li:nth-child(2):before, .agrupador-sextuplo .destaques li:before, .agrupador-musica-triplo .destaques li:before, .agrupador-sextuplo .destaques li:first-child:before, .agrupador-musica-triplo .destaques li:first-child:before, .agrupador-musica-triplo .top-container .foto:before, .box-complementar-uber li:before, .widget .box-widgets-personalizaveis.analytics-area .widget-highlights .area-topo:before,.topglobocom .topglobocom3 .mais-vistas .entretenimento li:before, .topglobocom .topglobocom3 .mais-vistas .esportes li:before, .topglobocom .topglobocom3 .mais-vistas .noticias li:before{background:##border;border-color:##border;}header,.link-see-more,.mobile-grid-full,.topglobocom .topglobocom3 .mais-vistas .entretenimento li, .topglobocom .topglobocom3 .mais-vistas .esportes li, .topglobocom .topglobocom3 .mais-vistas .noticias li{background:##bg;}\"},{host:/^([^.]+\\.)?mail\\.ru$/,append:'*:after{background-color:##border;}.block{box-shadow:0 2px 0 ##border;}.weather:before,.w-tabs:before,.w-tabs:after{background:none;}[class*=\"image\"]{opacity:0.7;}'},{host:/^[^.]+\\.liebao\\.cn$/,append:\"h2,div,strong{background-color:transparent;}.android-btn,.iphone-btn{opacity:0.7;}.game-item-play{background-color:##borderFocus;}\"},{host:/^[^.]+\\.cmcm\\.com$/,append:\".bg{background:none;}h2,h4,div,strong{background-color:transparent;}.active{outline:3px solid ##border;}.game-item-play{background-color:##borderFocus;}\"},{host:/^ssdk\\.adkmob\\.com$/,append:\".btn-dl{background-color:##border;box-shadow:0 2px 1px ##borderFocus;}.app-name:after{background:none;}\"},{host:/\\.twitter\\.com$/,append:\".content, .content *{background-color:transparent;}views,view,content{background-color:##bg;}#brand_bar{background-color:#50a7e6;}#brand_bar *{background-color:transparent;}\"},{host:/(?:\\.|^)web\\.de$/,append:\".teaser-wrapper,.teaser-wrapper *{background:none;}\"},{host:/\\.ruten\\.com\\.tw$/,append:\".page-header .main-menu ul.list li,.page-header .main-menu ul.list li span,.adver-text1,.clss-promo ul li:not(.cp-pchomepay){background:##border;}.clss-promo ul li *{background-color:transparent;}.cp-pchomepay,.clss-promo h2{opacity:0.7}.title,.title span,.hide{background:##border;}.view{background:##borderFocus;}.adver-list{background-color:transparent;}.top-sellers li,.catalogue li h3{background:none;}\"},{host:/(?:\\.|^)ask\\.fm/,append:\"html{background:##bg;}.signupButton{background:##border;box-shadow:none;}#menu,#whosHere-label,#shareLinkReminder{background:##border;}#menu *,#shareLinkReminder *{background-color:transparent;border-color:##borderFocus;}\"},{host:/\\.milanuncios\\.com$/,append:\".cabbg,.x1,.buscanuncios{background:none;}.dimg,.logo,.f1{opacity:0.7}\"},{host:/\\.naver\\.com$/,append:\".ham,img,.imsv{opacity:0.7;background-color:transparent;}.sch_w,.sch_inpw_in,.sch_inpw_in:before,.sch_inpw_in:after{background:##borderFocus;}.im,.imh,.sprh,.sp_rtk,.spuio,.imwt,.imw,.sc_psn .sc_psn_stt .sc_psn_a:before,.imhid,.id_hidden .sbl .sb_btns{color:transparent;opacity:0.7;}.dmm{background:rgba(0,0,0,0.5);}header span,header em{color:transparent;}html header{background-color:#3f63bf;opacity:0.7;}html header *{background-color:transparent;}.sc_cmt_wrp .sc_btn,.sc_err_wrp .sc_btn{box-shadow:none;}#video_area,#video_area *{background-color:transparent;}footer,footer *{background-color:transparent;}.home_poll .poll_lst li a,footer a{background-image:none;}.uio_link .ul_item:before,.uio_link .ul_item:after{background-color:##border;}\"},{host:/\\.dcinside\\.com$/,append:\".m_logo{background:none;}.issue_day,.btn_off,.img_comm,.box_rebtn .recomm{opacity:0.7;}.main_menu ul li{background:none;}.ng_icon a,.btn_extend,.btn_more,.btn_delete{background:##borderFocus;box-shadow:none;}.arr_tab_b,.arr_tab{display:none;}.m_search,.ng_box{background:##border;}.btn{background:##border;color:##text;}\"},{host:/\\.cnn\\.com$/,append:\"#smartbanner{background:none;}#smartbanner .sb-button{background:##border;box-shadow:none;}#smartbanner .sb-icon{opacity:0.7;}.section_header,.section_header_lower,.module_bgroup .cathd{background:##border;}.pagenav{opacity:0.7;}\"},{host:/(?:\\.|^)as\\.com$/,append:\".cnt-media-msg,.cnt-media-msg *,.hdr-in-nav,.publi_apuesta_iframe_2,.ntc-apoyos *{background:none;}.ntc-media-msg{background:rgba(0,0,0,0.5);}.res-p-marcador.finalizado,.res-p, .res-p-doble,.banner_sup:before,.banner_sup:after,.hdr-p,.btn-clasificacion,.modulo_escudos,.hdr-in-secondary,.hdr-buscador,.hdr-buscador-buscar2,.hdr-in-buscar,.hdr-secondary-aux,.hdr-in-nav:before,.tit-module-external,.tit-module-external:before,.ntc-apoyos,.tit-opi,.tit-module-internal:before,.ntc-opinion, .ntc-apoyo,.mdl-video-portadilla-black,.tit-module-media, .tit-module-gris-oscuro,.tit-module-media:before, .tit-module-gris-oscuro:before,.hdr-carrusel,.mdl-inf-header div,.tit-module-elpais,h3,.ftr_inf{background:##border;}.btn-clasificacion:before{box-shadow:none;}.activo{background:##borderFocus;}.hdr-in-secondary *,.hdr-p *,.s-left{background-color:transparent;}.tabs-opn{opacity:0.7}\"},{host:/\\.amazon\\.\\w+$/,append:\"#nav-backtotop,.a-button-inner,.a-button,.a-expander-header,.nav-a{background:##border;box-shadow:none;}#nav-logobar,.a-global-nav-wrapper{background:##bg;}.a-global-nav-wrapper *,#nav-logobar *{background-color:transparent;}#customerReviewsSmallStars,.a-icon{opacity:0.7;}.nav-search-submit .nav-input,html input.a-button-input[type=submit]{opacity:0.01;}.a-color-alternate-background{background:transparent;}\"},{host:/(?:\\.|^)searchmobileonline\\.com$/,append:\".top_nav_tab{background:##border;}.app-row{background:##border;}.app-row *{background-color:transparent;}\"},{host:/\\.baidu\\.com$/,append:\".se-bn *,#index-bn,#index-bn *{color:#000;}.se-input,.se-encode{background:##border;}.xs-image img{opacity:1;}.form-item{background-color:##border;}.plus-edit ul{background-color:##border;}#index-modal{background-color: rgba(9,9,9,.3);}#search-card .cur,.h-tab .cur{background:##border;}.imglist li,.hotlist li,.searchbox,.searchbox *,.searchbox input:hover{background-color:##border;}.searchbox .searchbox-btn{background:##link;color:#fff;}.baiduapp-icon{background-color: transparent;}.baiduapp-icon:before{border-top-color: #717077;}.callicon-wrap{background-color: transparent;}#admin-view .slide{background: #c7c7c7;}#admin-view .slide.on{background: #1bc059;}\"},{host:/(?:\\.|^)aliexpress\\.com$/,append:\".ui-button-normal,.ui-button-normal:link,.ui-button-normal:active,.ui-button-third{background:##border;}header{background:##bg;}\"},{host:/(?:\\.|^)blic\\.rs$/,append:\".button2,.button2_off{background:##border;color:##text;box-shadow:none;}\"},{host:/(?:\\.|^)omegle\\.com$/,append:\".youmsggroup .msggroup-msg{background:##border;}.strangermsggroup .msggroup-msg{background:##borderFocus;}\"},{host:/(?:\\.|^)varzesh3\\.com$/,append:\"font{color:##text;}\"},{host:/^v\\.m\\.liebao\\.cn$/,css:function(){return t.replace(/html a(?::[a-z]+)?(?: \\*)?/gi,\"$&:not(.btn)\")+\".detail_cover img,.banner_wrap img,img.cover_img{opacity:1;}#nav .news_all a:before{box-shadow:none;}.trans_layer,.page_layer{background-color:rgba(0,0,0,.3);}.list_condition a.cur{background:##borderFocus;}.right_side{background-color:transparent;}.update_tip{background:##borderFocus;}.update_tip:after{border-color:##borderFocus;}.search_latest li a,.search_hot li a,.form_search,.search_mask{background-color:##border;}.ico_filter{color:##text;}#nav a.cur{border-color: #527899;}#nav.news_nav a.cur span{border-color: #527899;}\"}},{host:/^m\\.58\\.com$/,append:'.city_box h4 p{background-color:transparent;}iframe[src^=\"http://static.track.58.com/\"]{background-color:##text;}.pc_banner img{z-index:0;}'},{host:/^m\\.freexs\\.cn$/,append:\".tfanye,.bfanye{background-color:transparent;}\"},{host:/^m\\.che168\\.com$/,append:\".topback-layer{background-color:transparent;}\"},{host:/(?:\\.|^)m\\.duba\\.com$/,append:\".site_logos li a.active{background:none;}.joke-cai,.joke-ding{background:none;}.imgbox i,.meitu-list ul li em{background-color:rgba(0,0,0,.7);}.btn_list li:first-child a,.links li a:first-child{color:#fff;}.meitu-nav ul li.on a,.novel-tab ul li.on{background:##border;}\"},{host:/waimai\\.baidu\\.com$/,append:\"#position-widget-city,#position-widget-city *,.history-title{background-color:transparent;}\"},{host:/mobile\\.baidu\\.com$/,append:\"app-card{background-color:transparent;border-color:##border;}.text-card .desc-more, .inapp-content .desc-more{background:-webkit-linear-gradient(left,rgba(0,0,0,.8),##border 20%);}.search-placeholder{background-color: #2D2C2B;}\"},{host:/image\\.baidu\\.com$/,append:\".searchbox,.searchbox form.fm,.searchbox .searchbox-wrap .searchbox-inline .searchbox-input input,.searchbox .searchbox-wrap .searchbox-inline .searchbox-input input:focus{background-color:##border;}.searchbox .searchbox-btn{background-image:none;}\"},{host:/baike\\.baidu\\.com$/,css:function(){return t.replace(/div/gi,\"$&:not(.toolbar-container)\")+\"html .toolbar-container *,p{background-color:transparent;}.search-button{background:##border;color:##text;}\"}},{host:/^m\\.zongheng\\.com$/,append:\".navigator>:nth-child(-n+2){background:##border;}.menu{background:none;}\"},{host:/^m\\.jiayuan\\.com$/,append:\".login_bg div{background-color: transparent;}.login_bg{background:none; background-color:##bg;}.login_btn{background-color: ##border; box-shadow: 0px 1px 1px #5C5C5C;}.login_list a{background-color:##border;}\"},{host:/(?:\\.|^)17k\\.com$/,css:function(){return t.replace(/label/g,\"_label\")+\".Menu{background:none;}\"}},{host:/(?:\\.|^)sohu\\.com$/,append:\".player_controls,.player_controls *,.video_title,.video_title *,.player .gg_area{background-color:transparent;}header .head{background:##border;}\"},{host:/(?:\\.|^)youku\\.com$/,append:\".x-player,.x-player *{background-color:transparent;}.v *,.p *{background-color:transparent;}.x-player .x-video-info .x-mask{background: #000;}\"},{host:/(?:\\.|^)v\\.qq\\.com$/,css:function(){return t.replace(/div|span/g,'$&:not([class^=\"tvp_\"])')}},{host:/(?:\\.|^)tudou\\.com$/,append:\".play-view,.play-view *{background-color:transparent;}\"},{host:/(?:\\.|^)iqiyi\\.com$/,append:\".mod-news,.mod-news:after{background:none;}.mod-news *{background:##border;}\"},{host:/(?:\\.|^)ganji\\.com$/,append:\".thumb-img-indexs,.zhiweichengnuo{background:none;}.feedback-links{background:##border;}.im-msg{background:none;}\"},{host:/(?:\\.|^)sina\\.cn$/,append:\".news_list .news_list_img img,.swipe_pic img,.carditems_list_dt img{opacity:1;}\"},{host:/^m\\.anjuke\\.com$/,append:\".imgblock .pintro,#pnav{background-color: transparent;}.imgblock .pintro .pinfo{background-color: rgba(0,0,0,0.6);}.imgblock .pnav li{  background: #c4c4c4;}.imgblock .pnav .focus{background: #62ab00;}.subblock .tgop, .subblock .natop{background: #e54c00;}.subblock .kftop, .subblock .ykop{  background: #51a308;}.I .m2{background:none;}.Gs2{background-image: -webkit-gradient(linear,0 0,0 100%,from(#525252),to(#0D0D0D));}.Gs2 a{color: #a8ecff;}.spTab{background-image:none;}.spTab .active{border-color:#969698;}.sx,.I .m2 label, .I .d1 label{background-image:none;}.m2 label span, .d1 label span{background-color:#97a3ad;}.sxr .tapping{color: #333;}.fangdongNum{background-image:none;}.b1 .active, .b1 .active1,.mainmenu .active{background-color:#151413;}.b1 .active,.mainmenu .active{color:#fff;}\"},{host:/^m\\.mh\\.9724\\.com$/,append:\".btn_blue{background:##border;} .btn_bubble{background: rgba(54,60,66,.92);}.show_more{background: -webkit-linear-gradient(left,rgba(250,247,245,0) 0,rgba(0, 0, 0, 1) 20%,rgba(21, 20, 19, 1) 100%);}.show_more:after{border-color:#00c8ff;}\"},{host:/^m\\.ly\\.com$/,append:\"#commonUpLayer{background: rgba(0,0,0,.7);}.pic_mask h3{background-color: transparent;}.ticket dt,.scenery-neary,.ticket dt{background:none;}.pic_mask{background: linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));background: -moz-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));background: -webkit-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));background: -o-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));background: -ms-linear-gradient(top,rgba(0,0,0,0),rgba(0,0,0,0.6));}.detail_nav li .activate span{border-color:#6D8193;}.header-menu-btn:before, .header-menu-btn i, .header-menu-btn:after{background: #00c8ff;}.page-back:before{border-color:#00c8ff;}.pbngdda-nsnwbwl,.pbngdda-nsnwbwl p{background: #636363;}.pbngdda-nsnwbwl div p:last-child{margin-top:0; padding-top:1px;}.content{background:none;}.content p{background-color: transparent;}\"},{host:/^passport\\.ly\\.com$/,append:\".inputcontent p,.inputcontent input,.inputcontent input:hover,.inputcontent input:focus{background:##border;}.inputcontent p:first-child i,.inputcontent p:nth-child(2) i{background-color:##border;}.btn-blue{background-color:##border;}\"},{host:/^m\\.xxsy\\.net$/,append:\".tab li.animbg{border-bottom: 3px solid ##border;}.tab > ul,.tab > ul > li{background-color: transparent;}\"},{host:/m\\.yiche\\.com$/,append:\".m-focus-box .pagination-focus{background-color:transparent;}.m-focus-box .swiper-pagination-switch{background: #9DA2A3;}.m-focus-box .swiper-active-switch{background: #C00;}.m-focus-box a.arrow-left, .m-focus-box a.arrow-right{height:60px;}.video-play-box > div,#x-player > div:not(.x-dashboard){background-color: transparent;}.x-mask{background: #000;}\"},{host:/m\\.tiexue\\.net$/,append:\".swipe .wrap span{background-color: rgba(0, 0, 0, 0.4);}#position li,#position span,#position span em,#position{background-color: transparent;}#jujiaoTab a{  background: #c6c6c6;}#jujiaoTab .on{background: #c5020d;}\"},{host:/m\\.xinjunshi\\.com$/,append:\".navitems,.swiper .pagination,.footer,ul.navitems_f{background:none;}.swiper .swiper-pagination-switch{background: #a9a89d;  border: 1px solid rgba(0,0,0,0.6);}.swiper .swiper-active-switch{  border: 1px solid #43e2fd;background: #58d8ff;}.r-paging-button{background:##border;}\"},{host:/budejie\\.com$/,append:\"#post-tab .active{background-color:##border;}\"},{host:/(?:\\.|^)ifeng\\.com$/,css:function(){return t.replace(/opacity/g,\"__opacity\")+\".module_title{background:##border;}\"}},{host:/^m\\.kuaidi100\\.com$/,append:\"nav{background:##border;}\"}];if(location.hostname)for(var e=c.length-1;e>-1;--e){var b=c[e],i=b.host,s=!1;if(i?i.test(location.hostname)&&(s=!0):b.reg.test(location.href)&&(s=!0),s){var l=b.css;n=\"string\"==typeof l?l:\"function\"==typeof l?l():t+b.append;break}}else n=t.replace(/outline/g,\"__outline\").replace(/:after/,\":not(.i-video i):after\")+\".box-border-wap{background-color:transparent;}.news-hotword a{background: ##border;}\";\"string\"!=typeof n&&(n=t);var u={bg:\"#151413\",text:\"#fff9e8\",link:\"#00c8ff\",linkVisited:\"#a8ecff\",border:\"#212A32\",borderFocus:\"#1A3973\"};d.href=\"data:text/css,\"+n.replace(/;/g,\"!important;\").replace(/##([a-z]+)/gi,function(o,r){return u.hasOwnProperty(r)?u[r]:o}),o(\"夜间模式样式生成完毕\")}function t(){!l&&document.documentElement&&(l=!0,clearInterval(i),document.removeEventListener(\"readystatechange\",t,!1),document.removeEventListener(\"DOMContentLoaded\",t,!1),window.removeEventListener(\"load\",t,!1),o(\"夜间模式样式异步初始化\"),n())}if(!window.__lb_nightModeJSInjected){window.__lb_nightModeJSInjected=!0;var c;c=\"undefined\"!=typeof performance&&performance.now?function(){return performance.now()}:function(){return Date.now()};o(\"夜间模式运行\");var d=document.createElement(\"link\");d.rel=\"stylesheet\";var b=\"lb_night_style\";d.id=b;var i,s=!0;if(__lb_night_call=function(r){o(\"夜间模式切换|\"+r),\"switch_day\"===r?a(!1):\"switch_night\"===r&&a(!0)},document.documentElement)o(\"夜间模式样式同步初始化\"),n();else{var l=!1,i=setInterval(t,16);document.addEventListener(\"readystatechange\",t,!1),document.addEventListener(\"DOMContentLoaded\",t,!1),window.addEventListener(\"load\",t,!1)}}}();";
	// private String
	// cccc="body{background-color:#151413 !important; color:#fff9e8 !important; border-color:#212a32 !important;}a{color:#00c8ff !important; border-color:#a8ecff !important;}a:visited{color:#a8ecff !important;}";
	// private Boolean isShow =true;
	private Boolean isNight = false;
	private StringBuilder localStringBuilder;
	private SharedPreferences preferences;	
	private String P_modelOne="R7Plusm";
	private String P_modelTwo="H7";
	private String P_modelThree="IUNI N1";

	// Log Tag
	private static final String LOGTAG = "kevint";// "Tab";
	private static final boolean LOGD_ENABLED = false;
	/** 广点通 */
	public static final String TAG_FROM_HOME_PAGE_GDT = "from_home_page_gdt";
	public static final String TAG_FROM_SITES_TOUTIAO = "tag_from_sites_toutiao";
	// Special case the logtag for messages for the Console to make it easier to
	// filter them and match the logtag used for these messages in older
	// versions
	// of the browser.
	private static final String CONSOLE_LOGTAG = "browser";

	private static final int MSG_CAPTURE = 42;
	private static final int CAPTURE_DELAY = 100;
	private static final int INITIAL_PROGRESS = 5;
	
	private int screenwidth=0;
	private int stopState = 2;
	private int lodingState = 0;
	private BaseUi mbaseUi;
	
	private static Bitmap sDefaultFavicon;

	private static Paint sAlphaPaint = new Paint();
	static {
		sAlphaPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
		sAlphaPaint.setColor(Color.TRANSPARENT);
	}

	public enum SecurityState {
		// The page's main resource does not use SSL. Note that we use this
		// state irrespective of the SSL authentication state of sub-resources.
		SECURITY_STATE_NOT_SECURE,
		// The page's main resource uses SSL and the certificate is good. The
		// same is true of all sub-resources.
		SECURITY_STATE_SECURE,
		// The page's main resource uses SSL and the certificate is good, but
		// some sub-resources either do not use SSL or have problems with their
		// certificates.
		SECURITY_STATE_MIXED,
		// The page's main resource uses SSL but there is a problem with its
		// certificate.
		SECURITY_STATE_BAD_CERTIFICATE,
	}

	Context mContext;
	protected WebViewController mWebViewController;

	// The tab ID
	private long mId = -1;

	// The Geolocation permissions prompt
	// DOING_FIXING_geolocation
	// private GeolocationPermissionsPrompt mGeolocationPermissionsPrompt;
	// The permissions prompt
	// DOING_FIXING_permission
	// private PermissionsPrompt mPermissionsPrompt;
	// Main WebView wrapper
	private View mContainer;
	// Main WebView
	public WebView mMainView;
	// Subwindow container
	private View mSubViewContainer;
	// Subwindow WebView
	private WebView mSubView;
	// Saved bundle for when we are running low on memory. It contains the
	// information needed to restore the WebView if the user goes back to the
	// tab.
	private Bundle mSavedState;
	// Parent Tab. This is the Tab that created this Tab, or null if the Tab was
	// created by the UI
	private Tab mParent;
	// Tab that constructed by this Tab. This is used when this Tab is
	// destroyed, it clears all mParentTab values in the children.
	private Vector<Tab> mChildren;
	// If true, the tab is in the foreground of the current activity.
	private boolean mInForeground;
	// If true, the tab is in page loading state (after onPageStarted,
	// before onPageFinsihed)
	private boolean mInPageLoad;
	private boolean mDisableOverrideUrlLoading;
	// The last reported progress of the current page
	private int mPageLoadProgress;
	// The time the load started, used to find load page time
	private long mLoadStartTime;
	// Application identifier used to find tabs that another application wants
	// to reuse.
	private String mAppId;
	// flag to indicate if tab should be closed on back
	private boolean mCloseOnBack;
	// Keep the original url around to avoid killing the old WebView if the url
	// has not changed.
	// Error console for the tab
	// private ErrorConsoleView mErrorConsole;
	// The listener that gets invoked when a download is started from the
	// mMainView
	private final BrowserDownloadListener mDownloadListener;
	// Listener used to know when we move forward or back in the history list.
	private final WebBackForwardListClient mWebBackForwardListClient;
	private DataController mDataController;
	// State of the auto-login request.
	// private DeviceAccountLogin mDeviceAccountLogin;

	// AsyncTask for downloading touch icons
	DownloadTouchIcon mTouchIconLoader;

	private BrowserSettings mSettings;
	private int mCaptureWidth;
	private int mCaptureHeight;
	private Bitmap mCapture;
	private Handler mHandler;
	private boolean mUpdateThumbnail;

	private int mHomePagePosition;
	public String addressUrl;

	/**
	 * See {@link #clearBackStackWhenItemAdded(String)}.
	 */
	private Pattern mClearHistoryUrlPattern;

	private static synchronized Bitmap getDefaultFavicon(Context context) {
		if (sDefaultFavicon == null) {
			sDefaultFavicon = BitmapFactory.decodeResource(
					context.getResources(), R.drawable.br_app_web_browser_sm);
		}
		return sDefaultFavicon;
	}

	// All the state needed for a page
	protected static class PageState {
		String mUrl;
		String mOriginalUrl;
		String mTitle;
		SecurityState mSecurityState;
		// This is non-null only when mSecurityState is
		// SECURITY_STATE_BAD_CERTIFICATE.
		SslError mSslCertificateError;
		Bitmap mFavicon;
		boolean mIsBookmarkedSite;
		boolean mIncognito;

		HomePagePara mHomePagePara;
		long mStartLoadTime;

		PageState(Context c, boolean incognito) {
			mIncognito = incognito;
			if (mIncognito) {
				mOriginalUrl = mUrl = "browser:incognito";
				mTitle = c.getString(R.string.new_incognito_tab);
			} else {
				mOriginalUrl = mUrl = "";
				mTitle = c.getString(R.string.new_tab);
			}
			mSecurityState = SecurityState.SECURITY_STATE_NOT_SECURE;
		}

		PageState(Context c, boolean incognito, String url, Bitmap favicon) {
			mIncognito = incognito;
			mOriginalUrl = mUrl = url;
			if (URLUtil.isHttpsUrl(url)) {
				mSecurityState = SecurityState.SECURITY_STATE_SECURE;
			} else {
				mSecurityState = SecurityState.SECURITY_STATE_NOT_SECURE;
			}
			mFavicon = favicon;
		}

	}

	static class HomePageState extends PageState {

		HomePageState(Context c, boolean incognito, String url, Bitmap favicon) {
			super(c, incognito, url, favicon);
			mTitle = c.getResources().getString(R.string.homepage_base_title);

		}

		HomePageState(Context c, String url) {
			this(c, false, url, null);
		}
	}

	// The current/loading page's state
	protected PageState mCurrentState;
	protected PageState mOldState;

	// Used for saving and restoring each Tab
	static final String ID = "ID";
	static final String CURRURL = "currentUrl";
	static final String CURRTITLE = "currentTitle";
	static final String PARENTTAB = "parentTab";
	static final String APPID = "appid";
	static final String INCOGNITO = "privateBrowsingEnabled";
	static final String USERAGENT = "useragent";
	static final String CLOSEFLAG = "closeOnBack";

	// protected final Runnable MyRunable = null;

	// Container class for the next error dialog that needs to be displayed
	private class ErrorDialog {
		public final int mTitle;
		public final String mDescription;
		public final int mError;

		ErrorDialog(int title, String desc, int error) {
			mTitle = title;
			mDescription = desc;
			mError = error;
		}
	}

	private void processNextError() {
		if (mQueuedErrors == null) {
			return;
		}
		// The first one is currently displayed so just remove it.
		mQueuedErrors.removeFirst();
		if (mQueuedErrors.size() == 0) {
			mQueuedErrors = null;
			return;
		}
		// showError(mQueuedErrors.getFirst());
	}

	private DialogInterface.OnDismissListener mDialogListener = new DialogInterface.OnDismissListener() {
		public void onDismiss(DialogInterface d) {
			processNextError();
		}
	};
	private LinkedList<ErrorDialog> mQueuedErrors;

	private void queueError(int err, String desc) {
		if (mQueuedErrors == null) {
			mQueuedErrors = new LinkedList<ErrorDialog>();
		}
		for (ErrorDialog d : mQueuedErrors) {
			if (d.mError == err) {
				// Already saw a similar error, ignore the new one.
				return;
			}
		}
		ErrorDialog errDialog = new ErrorDialog(
				err == WebViewClient.ERROR_FILE_NOT_FOUND ? R.string.browserFrameFileErrorLabel
						: R.string.browserFrameNetworkErrorLabel, desc, err);
		mQueuedErrors.addLast(errDialog);

		// Show the dialog now if the queue was empty and it is in foreground
		if (mQueuedErrors.size() == 1 && mInForeground) {
			// showError(errDialog);
		}
	}

	private void showError(ErrorDialog errDialog) {
		if (mInForeground) {
			AlertDialog d = new AlertDialog.Builder(mContext)
					.setTitle(errDialog.mTitle)
					.setMessage(errDialog.mDescription)
					.setPositiveButton(R.string.ok, null).create();
			d.setOnDismissListener(mDialogListener);
			d.show();
		}
	}

	// -------------------------------------------------------------------------
	// WebViewClient implementation for the main WebView
	// -------------------------------------------------------------------------

	private final WebViewClient mWebViewClient = new WebViewClient() {
		private Message mDontResend;
		private Message mResend;

		private boolean providersDiffer(String url, String otherUrl) {
			Uri uri1 = Uri.parse(url);
			Uri uri2 = Uri.parse(otherUrl);
			return !uri1.getEncodedAuthority().equals(
					uri2.getEncodedAuthority());
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			
//			if(mbaseUi!=null){
//				mbaseUi.showOnlyFixTile(false);
//			}

			if(url!=null&&url.contains("www.12306.cn")){
				if(screenwidth>540){
				view.getSettings().setTextZoom(50);
				}
			}
			//记录书架url
			if (null != url && !"".equals(url) && url.contains("ks.baidu.com/book/read?fr=moxiu")) {
				BrowserSettings.getInstance().setNovelHabit(false);
			}
			if (isNight) {
				view.loadUrl(localStringBuilder.toString());;
			}
			refreshBit(0);

			// if (isShowingHomePage()) {
			// hideHomePage();
			// }

			mInPageLoad = true;
			mUpdateThumbnail = true;
			mPageLoadProgress = INITIAL_PROGRESS;
			if (url != null && !url.equals(mCurrentHomePageArticleUrl)) {
				reportHomePageArticleReadTime();
			}

			mCurrentState = new PageState(mContext,
					view.isPrivateBrowsingEnabled(), url, favicon);
			if (url != null && url.equals(mCurrentHomePageArticleUrl)) {
				mCurrentState.mHomePagePara = mCurrentHomePagePara;
				mCurrentState.mStartLoadTime = System.currentTimeMillis();
				restoreHomePageActicleReadPara();
			}
			mLoadStartTime = SystemClock.uptimeMillis();

			// If we start a touch icon load and then load a new page, we don't
			// want to cancel the current touch icon loader. But, we do want to
			// create a new one when the touch icon url is known.
			if (mTouchIconLoader != null) {
				mTouchIconLoader.mTab = null;
				mTouchIconLoader = null;
			}

			// reset the error console
			// if (mErrorConsole != null) {
			// mErrorConsole.clearErrorMessages();
			// if (mWebViewController.shouldShowErrorConsole()) {
			// mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
			// }
			// }

			// Cancel the auto-login process.
			// if (mDeviceAccountLogin != null) {
			// mDeviceAccountLogin.cancel();
			// mDeviceAccountLogin = null;
			// mWebViewController.hideAutoLogin(Tab.this);
			// }

			// finally update the UI in the activity if it is in the foreground
			mWebViewController.onPageStarted(Tab.this, view, favicon);

			updateBookmarkedStatus();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
	       if (isNight) {
				view.loadUrl(localStringBuilder.toString());			
			}
	       BrowserJsInject.getInstance().jsInject(view, url);
	       mDisableOverrideUrlLoading = false;
			if (!isPrivateBrowsingEnabled()) {
				// LogTag.logPageFinishedLoading(
				// url, SystemClock.uptimeMillis() - mLoadStartTime);
			}
			syncCurrentState(view, url);
			mWebViewController.onPageFinished(Tab.this);
			mHasLoadedPage = true;
		}

		// String mCurrentUrl;
		// return true if want to hijack the url to let another app to handle it
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {		

			if (url.startsWith("mailto:") || url.startsWith("geo:") ||url.startsWith("tel:")||url.startsWith("sms:")) {  
				Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url)); 
				mContext.startActivity(intent); 
				return true;
			} 
		
			if (!mDisableOverrideUrlLoading && mInForeground) {
				return mWebViewController.shouldOverrideUrlLoading(Tab.this,
						view, url);
			} else {
				return false;
			}
		}

		/**
		 * Updates the security state. This method is called when we discover
		 * another resource to be loaded for this page (for example,
		 * javascript). While we update the security state, we do not update the
		 * lock icon until we are done loading, as it is slightly more secure
		 * this way.
		 */
		@Override
		public void onLoadResource(WebView view, String url) {
			if (url != null && url.length() > 0) {
				// It is only if the page claims to be secure that we may have
				// to update the security state:
				if (mCurrentState.mSecurityState == SecurityState.SECURITY_STATE_SECURE) {
					// If NOT a 'safe' url, change the state to mixed content!
					if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil
							.isAboutUrl(url))) {
						mCurrentState.mSecurityState = SecurityState.SECURITY_STATE_MIXED;
					}
				}
				if (isNight) {
					view.loadUrl(localStringBuilder.toString());
				}
			}
		}
		/**
		 * Show a dialog informing the user of the network error reported by
		 * WebCore if it is in the foreground.
		 */
		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			if (errorCode != WebViewClient.ERROR_HOST_LOOKUP
					&& errorCode != WebViewClient.ERROR_CONNECT
					&& errorCode != WebViewClient.ERROR_BAD_URL
					&& errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME
					&& errorCode != WebViewClient.ERROR_FILE) {

				queueError(errorCode, description);

				// Don't log URLs when in private browsing mode
				if (!isPrivateBrowsingEnabled()) {
					Log.e(LOGTAG, "onReceivedError " + errorCode + " "
							+ failingUrl + " " + description);
				}
			}

			// if (mMainView != null && mErrorView.getParent() == null) {
			// mMainView.addView(mErrorView, mErrorParam);
			// mErrorView.bringToFront();
			// }
		}

		/**
		 * Check with the user if it is ok to resend POST data as the page they
		 * are trying to navigate to is the result of a POST.
		 */
		@Override
		public void onFormResubmission(WebView view, final Message dontResend,
				final Message resend) {
			if (!mInForeground) {
				dontResend.sendToTarget();
				return;
			}
			if (mDontResend != null) {
				Log.w(LOGTAG, "onFormResubmission should not be called again "
						+ "while dialog is still up");
				dontResend.sendToTarget();
				return;
			}
			mDontResend = dontResend;
			mResend = resend;
			new AlertDialog.Builder(mContext)
					.setTitle(R.string.browserFrameFormResubmitLabel)
					.setMessage(R.string.browserFrameFormResubmitMessage)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									if (mResend != null) {
										mResend.sendToTarget();
										mResend = null;
										mDontResend = null;
									}
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									if (mDontResend != null) {
										mDontResend.sendToTarget();
										mResend = null;
										mDontResend = null;
									}
								}
							}).setOnCancelListener(new OnCancelListener() {
						public void onCancel(DialogInterface dialog) {
							if (mDontResend != null) {
								mDontResend.sendToTarget();
								mResend = null;
								mDontResend = null;
							}
						}
					}).show();
		}

		/**
		 * Insert the url into the visited history database.
		 * 
		 * @param url
		 *            The url to be inserted.
		 * @param isReload
		 *            True if this url is being reloaded. FIXME: Not sure what
		 *            to do when reloading the page.
		 */
		@Override
		public void doUpdateVisitedHistory(WebView view, String url,
				boolean isReload) {
			Log.e("doUpdateVisitedHistory", "doUpdateVisitedHistory");
			mWebViewController.doUpdateVisitedHistory(Tab.this, isReload);
		}

		/**
		 * Displays SSL error(s) dialog to the user.
		 */
		@Override
		public void onReceivedSslError(final WebView view,
				final SslErrorHandler handler, final SslError error) {
			if (!mInForeground) {
				handler.cancel();
				setSecurityState(SecurityState.SECURITY_STATE_NOT_SECURE);
				return;
			}
			// DOING_FIXING_showsecuritywarnings
			if (mSettings.showSecurityWarnings()) {
				new AlertDialog.Builder(mContext)
						.setTitle(R.string.security_warning)
						.setMessage(R.string.ssl_warnings_header)
						.setIconAttribute(android.R.attr.alertDialogIcon)
						.setPositiveButton(R.string.ssl_continue,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int whichButton) {
										handler.proceed();
										handleProceededAfterSslError(error);
									}
								})
						.setNeutralButton(R.string.view_certificate,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int whichButton) {
										mWebViewController
												.showSslCertificateOnError(
														view, handler, error);
									}
								})
						.setNegativeButton(R.string.ssl_go_back,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int whichButton) {
										dialog.cancel();
									}
								})
						.setOnCancelListener(
								new DialogInterface.OnCancelListener() {
									@Override
									public void onCancel(DialogInterface dialog) {
										handler.cancel();
										setSecurityState(SecurityState.SECURITY_STATE_NOT_SECURE);
										mWebViewController
												.onUserCanceledSsl(Tab.this);
									}
								}).show();
			} else {
				handler.proceed();
				handleProceededAfterSslError(error);
			}
		}

		/**
		 * Displays client certificate request to the user.
		 */
		@Override
		public void onReceivedClientCertRequest(final WebView view,
				final ClientCertRequest request) {
			if (!mInForeground) {
				request.ignore();
				return;
			}
			KeyChain.choosePrivateKeyAlias(mWebViewController.getActivity(),
					new KeyChainAliasCallback() {
						@Override
						public void alias(String alias) {
							if (alias == null) {
								request.cancel();
								return;
							}
							new KeyChainLookup(mContext, request, alias)
									.execute();
						}
					}, request.getKeyTypes(), request.getPrincipals(), request
							.getHost(), request.getPort(), null);
		}

		/**
		 * Handles an HTTP authentication request.
		 *
		 * @param handler
		 *            The authentication handler
		 * @param host
		 *            The host
		 * @param realm
		 *            The realm
		 */
		@Override
		public void onReceivedHttpAuthRequest(WebView view,
				final HttpAuthHandler handler, final String host,
				final String realm) {
			mWebViewController.onReceivedHttpAuthRequest(Tab.this, view,
					handler, host, realm);
		}

		@Override
		public WebResourceResponse shouldInterceptRequest(WebView view,
				String url) {
			
			if (isNight) {
				if (url.contains(".css")){
					view.loadUrl(localStringBuilder.toString());
				}
			}
			if (BrowserAdblockImpl.getInstance().adUrlMatching(url)) {
				url = "";
				return new WebResourceResponse(url, "utf-8", null);
			}
			return HomeProvider.shouldInterceptRequest(mContext, url);
		}
		
		@Override
		public WebResourceResponse shouldInterceptRequest(WebView view,
				WebResourceRequest request) {
			String url = request.getUrl().toString();
			if (BrowserAdblockImpl.getInstance().adUrlMatching(url)) {
				url = "";
				return new WebResourceResponse(url, "utf-8", null);
			}
			return super.shouldInterceptRequest(view, request);
		}

		@Override
		public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
			if (!mInForeground) {
				return false;
			}
			return mWebViewController.shouldOverrideKeyEvent(event);
		}

		@Override
		public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
			if (!mInForeground) {
				return;
			}
			if (!mWebViewController.onUnhandledKeyEvent(event)) {
				super.onUnhandledKeyEvent(view, event);
			}
		}

		@Override
		public void onReceivedLoginRequest(WebView view, String realm,
				String account, String args) {
			// new DeviceAccountLogin(mWebViewController.getActivity(), view,
			// Tab.this, mWebViewController)
			// .handleLogin(realm, account, args);
		}

	};

	private void syncCurrentState(WebView view, String url) {
		// Sync state (in case of stop/timeout)

		if (mCurrentState instanceof HomePageState) {
			return;
		}

		mCurrentState.mUrl = view.getUrl();
		if (mCurrentState.mUrl == null) {
			mCurrentState.mUrl = "";
		}
		mCurrentState.mOriginalUrl = view.getOriginalUrl();
		mCurrentState.mTitle = view.getTitle();
		mCurrentState.mFavicon = view.getFavicon();
		if (!URLUtil.isHttpsUrl(mCurrentState.mUrl)) {
			// In case we stop when loading an HTTPS page from an HTTP page
			// but before a provisional load occurred
			mCurrentState.mSecurityState = SecurityState.SECURITY_STATE_NOT_SECURE;
			mCurrentState.mSslCertificateError = null;
		}
		mCurrentState.mIncognito = view.isPrivateBrowsingEnabled();
	}

	// Called by DeviceAccountLogin when the Tab needs to have the auto-login UI
	// displayed.
	// void setDeviceAccountLogin(DeviceAccountLogin login) {
	// mDeviceAccountLogin = login;
	// }

	// Returns non-null if the title bar should display the auto-login UI.
	// DeviceAccountLogin getDeviceAccountLogin() {
	// return mDeviceAccountLogin;
	// }

	// -------------------------------------------------------------------------
	// WebChromeClient implementation for the main WebView
	// -------------------------------------------------------------------------

	private final WebChromeClient mWebChromeClient = new WebChromeClient() {
		// Helper method to create a new tab or sub window.
		private void createWindow(final boolean dialog, final Message msg) {
			WebView.WebViewTransport transport = (WebView.WebViewTransport) msg.obj;
			if (dialog) {
				createSubWindow();
				mWebViewController.attachSubWindow(Tab.this);
				transport.setWebView(mSubView);
			} else {
				final Tab newTab = mWebViewController.openTab(null, Tab.this,
						true, true);
				transport.setWebView(newTab.getWebView());
			}
			msg.sendToTarget();
		}

		@Override
		public boolean onCreateWindow(WebView view, final boolean dialog,
				final boolean userGesture, final Message resultMsg) {
			// only allow new window or sub window for the foreground case
			if (!mInForeground) {
				return false;
			}
			// Short-circuit if we can't create any more tabs or sub windows.
			if (dialog && mSubView != null) {
				new AlertDialog.Builder(mContext)
						.setTitle(R.string.too_many_subwindows_dialog_title)
						.setIconAttribute(android.R.attr.alertDialogIcon)
						.setMessage(R.string.too_many_subwindows_dialog_message)
						.setPositiveButton(R.string.ok, null).show();
				return false;
			} else if (!mWebViewController.getTabControl().canCreateNewTab()) {
				new AlertDialog.Builder(mContext)
						.setTitle(R.string.too_many_windows_dialog_title)
						.setIconAttribute(android.R.attr.alertDialogIcon)
						.setMessage(R.string.too_many_windows_dialog_message)
						.setPositiveButton(R.string.ok, null).show();
				return false;
			}

			// Short-circuit if this was a user gesture.
			if (userGesture) {
				createWindow(dialog, resultMsg);
				return true;
			}

			// Allow the popup and create the appropriate window.
			final AlertDialog.OnClickListener allowListener = new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface d, int which) {
					createWindow(dialog, resultMsg);
				}
			};

			// Block the popup by returning a null WebView.
			final AlertDialog.OnClickListener blockListener = new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface d, int which) {
					resultMsg.sendToTarget();
				}
			};

			// Build a confirmation dialog to display to the user.
			final AlertDialog d = new AlertDialog.Builder(mContext)
					.setIconAttribute(android.R.attr.alertDialogIcon)
					.setMessage(R.string.popup_window_attempt)
					.setPositiveButton(R.string.allow, allowListener)
					.setNegativeButton(R.string.block, blockListener)
					.setCancelable(false).create();

			// Show the confirmation dialog.
			d.show();
			return true;
		}

		@Override
		public void onRequestFocus(WebView view) {
			if (!mInForeground) {
				mWebViewController.switchToTab(Tab.this);
			}
		}

		@Override
		public void onCloseWindow(WebView window) {
			if (mParent != null) {
				// JavaScript can only close popup window.
				if (mInForeground) {
					mWebViewController.switchToTab(mParent);
				}
				mWebViewController.closeTab(Tab.this);
			}
		}

		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				JsResult result) {
			mWebViewController.getTabControl().setActiveTab(Tab.this);
			return false;
		}

		@Override
		public boolean onJsConfirm(WebView view, String url, String message,
				JsResult result) {
			
			// builder.setCancelable(false);
			// builder.create();
			// builder.show();

			mWebViewController.getTabControl().setActiveTab(Tab.this);
			return false;
		}

		@Override
		public boolean onJsPrompt(WebView view, String url, String message,
				String defaultValue, JsPromptResult result) {
			mWebViewController.getTabControl().setActiveTab(Tab.this);
			return false;
		}

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
        	if (isNight) {
				view.loadUrl(localStringBuilder.toString());
			}
			if (isShowingHomePage()) {
				mPageLoadProgress = 100;
				mWebViewController.onProgressChanged(Tab.this);
				return;
			}

			mPageLoadProgress = newProgress;
			if (newProgress == 100) {
				refreshBit(2);
				mInPageLoad = false;
			}
			mWebViewController.onProgressChanged(Tab.this);
			if (mUpdateThumbnail && newProgress == 100) {
				refreshBit(2);
				mUpdateThumbnail = false;
			}
		}

		@Override
		public void onReceivedTitle(WebView view, final String title) {
			if (mCurrentState instanceof HomePageState) {
				return;
			}
			mCurrentState.mTitle = title;
			mWebViewController.onReceivedTitle(Tab.this, title);
		}

		@Override
		public void onReceivedIcon(WebView view, Bitmap icon) {
			if (mCurrentState instanceof HomePageState) {
				return;
			}
			mCurrentState.mFavicon = icon;
			mWebViewController.onFavicon(Tab.this, view, icon);
		}

		@Override
		public void onReceivedTouchIconUrl(WebView view, String url,
				boolean precomposed) {
			final ContentResolver cr = mContext.getContentResolver();
			// Let precomposed icons take precedence over non-composed
			// icons.
			if (precomposed && mTouchIconLoader != null) {
				mTouchIconLoader.cancel(false);
				mTouchIconLoader = null;
			}
			// Have only one async task at a time.
			if (mTouchIconLoader == null) {
				mTouchIconLoader = new DownloadTouchIcon(Tab.this, cr, view);
				mTouchIconLoader.execute(url);
			}
		}

		@Override
		public void onShowCustomView(View view,
				WebChromeClient.CustomViewCallback callback) {
			Activity activity = mWebViewController.getActivity();
			if (activity != null) {
				onShowCustomView(view, activity.getRequestedOrientation(),
						callback);
			}
		}

		@Override
		public void onShowCustomView(View view, int requestedOrientation,
				WebChromeClient.CustomViewCallback callback) {
			if (mInForeground)
				mWebViewController.showCustomView(Tab.this, view,
						requestedOrientation, callback);
		}

		@Override
		public void onHideCustomView() {
			if (mInForeground)
				mWebViewController.hideCustomView();
		}

		/**
		 * The origin has exceeded its database quota.
		 * 
		 * @param url
		 *            the URL that exceeded the quota
		 * @param databaseIdentifier
		 *            the identifier of the database on which the transaction
		 *            that caused the quota overflow was run
		 * @param currentQuota
		 *            the current quota for the origin.
		 * @param estimatedSize
		 *            the estimated size of the database.
		 * @param totalUsedQuota
		 *            is the sum of all origins' quota.
		 * @param quotaUpdater
		 *            The callback to run when a decision to allow or deny quota
		 *            has been made. Don't forget to call this!
		 */
		@Override
		public void onExceededDatabaseQuota(String url,
				String databaseIdentifier, long currentQuota,
				long estimatedSize, long totalUsedQuota,
				WebStorage.QuotaUpdater quotaUpdater) {
			mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(url,
					databaseIdentifier, currentQuota, estimatedSize,
					totalUsedQuota, quotaUpdater);
		}

		/**
		 * The Application Cache has exceeded its max size.
		 * 
		 * @param spaceNeeded
		 *            is the amount of disk space that would be needed in order
		 *            for the last appcache operation to succeed.
		 * @param totalUsedQuota
		 *            is the sum of all origins' quota.
		 * @param quotaUpdater
		 *            A callback to inform the WebCore thread that a new app
		 *            cache size is available. This callback must always be
		 *            executed at some point to ensure that the sleeping WebCore
		 *            thread is woken up.
		 */
		@Override
		public void onReachedMaxAppCacheSize(long spaceNeeded,
				long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
			mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
					spaceNeeded, totalUsedQuota, quotaUpdater);
		}

		/**
		 * Instructs the browser to show a prompt to ask the user to set the
		 * Geolocation permission state for the specified origin.
		 * 
		 * @param origin
		 *            The origin for which Geolocation permissions are
		 *            requested.
		 * @param callback
		 *            The callback to call once the user has set the Geolocation
		 *            permission state.
		 */
		// DOING_FIXING_geolocation
		// @Override
		// public void onGeolocationPermissionsShowPrompt(String origin,
		// GeolocationPermissions.Callback callback) {
		// if (mInForeground) {
		// getGeolocationPermissionsPrompt().show(origin, callback);
		// }
		// }

		/**
		 * Instructs the browser to hide the Geolocation permissions prompt.
		 */
		// @Override
		// public void onGeolocationPermissionsHidePrompt() {
		// if (mInForeground && mGeolocationPermissionsPrompt != null) {
		// mGeolocationPermissionsPrompt.hide();
		// }
		// }
		// DOING_FIXING_permission
		// @Override
		// public void onPermissionRequest(PermissionRequest request) {
		// if (!mInForeground) return;
		// getPermissionsPrompt().show(request);
		// }
		// DOING_FIXING_permission
		// @Override
		// public void onPermissionRequestCanceled(PermissionRequest request) {
		// if (mInForeground && mPermissionsPrompt != null) {
		// mPermissionsPrompt.hide();
		// }
		// }

		/*
		 * Adds a JavaScript error message to the system log and if the JS
		 * console is enabled in the about:debug options, to that console also.
		 * 
		 * @param consoleMessage the message object.
		 */
		@Override
		public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
			if (mInForeground) {
				// call getErrorConsole(true) so it will create one if needed
				// ErrorConsoleView errorConsole = getErrorConsole(true);
				// errorConsole.addErrorMessage(consoleMessage);
				// if (mWebViewController.shouldShowErrorConsole()
				// && errorConsole.getShowState() !=
				// ErrorConsoleView.SHOW_MAXIMIZED) {
				// errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
				// }
			}

			// Don't log console messages in private browsing mode
			if (isPrivateBrowsingEnabled())
				return true;

			String message = "Console: " + consoleMessage.message() + " "
					+ consoleMessage.sourceId() + ":"
					+ consoleMessage.lineNumber();

			switch (consoleMessage.messageLevel()) {
			case TIP:
				Log.v(CONSOLE_LOGTAG, message);
				break;
			case LOG:
				Log.i(CONSOLE_LOGTAG, message);
				break;
			case WARNING:
				Log.w(CONSOLE_LOGTAG, message);
				break;
			case ERROR:
				Log.e(CONSOLE_LOGTAG, message);
				break;
			case DEBUG:
				Log.d(CONSOLE_LOGTAG, message);
				break;
			}

			return true;
		}

		/**
		 * Ask the browser for an icon to represent a <video> element. This icon
		 * will be used if the Web page did not specify a poster attribute.
		 * 
		 * @return Bitmap The icon or null if no such icon is available.
		 */
		@Override
		public Bitmap getDefaultVideoPoster() {
			if (mInForeground) {
				return mWebViewController.getDefaultVideoPoster();
			}
			return null;
		}

		/**
		 * Ask the host application for a custom progress view to show while a
		 * <video> is loading.
		 * 
		 * @return View The progress view.
		 */
		@Override
		public View getVideoLoadingProgressView() {

			if (mInForeground) {
				return mWebViewController.getVideoLoadingProgressView();
			}
			return null;
		}

		@Override
		public boolean onShowFileChooser(WebView webView,
				ValueCallback<Uri[]> callback, FileChooserParams params) {
			if (mInForeground) {
				mWebViewController.showFileChooser(callback, params);
				return true;
			} else {
				return false;
			}
		}

		/**
		 * Deliver a list of already-visited URLs
		 */
		@Override
		public void getVisitedHistory(final ValueCallback<String[]> callback) {
			mWebViewController.getVisitedHistory(callback);
		}

	};

	// -------------------------------------------------------------------------
	// WebViewClient implementation for the sub window
	// -------------------------------------------------------------------------

	// Subclass of WebViewClient used in subwindows to notify the main
	// WebViewClient of certain WebView activities.
	private static class SubWindowClient extends WebViewClient {
		// The main WebViewClient.
		private final WebViewClient mClient;
		private final WebViewController mController;

		SubWindowClient(WebViewClient client, WebViewController controller) {
			mClient = client;
			mController = controller;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// Unlike the others, do not call mClient's version, which would
			// change the progress bar. However, we do want to remove the
			// find or select dialog.
			mController.endActionMode();
		}

		@Override
		public void doUpdateVisitedHistory(WebView view, String url,
				boolean isReload) {
			mClient.doUpdateVisitedHistory(view, url, isReload);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			return mClient.shouldOverrideUrlLoading(view, url);
		}
		
		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			mClient.onReceivedSslError(view, handler, error);
		}

		@Override
		public void onReceivedClientCertRequest(WebView view,
				ClientCertRequest request) {
			mClient.onReceivedClientCertRequest(view, request);
		}

		@Override
		public void onReceivedHttpAuthRequest(WebView view,
				HttpAuthHandler handler, String host, String realm) {
			mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
		}

		@Override
		public void onFormResubmission(WebView view, Message dontResend,
				Message resend) {
			mClient.onFormResubmission(view, dontResend, resend);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			mClient.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public boolean shouldOverrideKeyEvent(WebView view,
				android.view.KeyEvent event) {
			return mClient.shouldOverrideKeyEvent(view, event);
		}

		@Override
		public void onUnhandledKeyEvent(WebView view,
				android.view.KeyEvent event) {
			mClient.onUnhandledKeyEvent(view, event);
		}
	}

	// -------------------------------------------------------------------------
	// WebChromeClient implementation for the sub window
	// -------------------------------------------------------------------------

	private class SubWindowChromeClient extends WebChromeClient {
		// The main WebChromeClient.
		private final WebChromeClient mClient;

		SubWindowChromeClient(WebChromeClient client) {
			mClient = client;
		}

		@Override
		public void onProgressChanged(WebView view, int newProgress) {

			mClient.onProgressChanged(view, newProgress);
		}

		@Override
		public boolean onCreateWindow(WebView view, boolean dialog,
				boolean userGesture, android.os.Message resultMsg) {
			return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
		}

		@Override
		public void onCloseWindow(WebView window) {
			if (window != mSubView) {
				Log.e(LOGTAG, "Can't close the window");
			}
			mWebViewController.dismissSubWindow(Tab.this);
		}
	}

	// -------------------------------------------------------------------------

	// Construct a new tab
	Tab(WebViewController wvcontroller, WebView w) {
		this(wvcontroller, w, null);
	}

	Tab(WebViewController wvcontroller, Bundle state) {
		this(wvcontroller, null, state);
	}

	private TextView mErrorView;
	private ViewGroup.LayoutParams mErrorParam;
	public B_BrowserMainManager mainManager;

	void initErrorView() {
		mErrorView = new TextView(mContext);
		mErrorView.setText("页面加载失败");
		mErrorView.setBackgroundColor(Color.parseColor("#333333"));
		mErrorView.setGravity(Gravity.CENTER);
		mErrorParam = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
	}

	Tab(WebViewController wvcontroller, WebView w, Bundle state) {

		localStringBuilder = new StringBuilder(
				"javascript:if(typeof __lb_night_call !== 'undefined'){__lb_night_call(\"switch_night\");}else{");
		/*
		 * try { cccc=readFile("file:///android_asset/night.js"); } catch
		 * (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
		localStringBuilder.append(cccc);
		localStringBuilder.append("}");
		mWebViewController = wvcontroller;
		mContext = mWebViewController.getContext();
		Controller controller=(Controller)mWebViewController;
		mbaseUi = (BaseUi)controller.getUi();
		mainManager=controller.getHomePage().mHBrowserMainManager;
		mSettings = BrowserSettings.getInstance();
		mDataController = DataController.getInstance(mContext);
		mCurrentState = new PageState(mContext,
				w != null ? w.isPrivateBrowsingEnabled() : false);
		mInPageLoad = false;
		mInForeground = false;

		
		  preferences = mContext.getSharedPreferences("default_night",
		  mContext.MODE_PRIVATE);
		  isNight=preferences.getBoolean("default_night", false);
		
		// initErrorView();

		mDownloadListener = new BrowserDownloadListener() {
			public void onDownloadStart(String url, String userAgent,
					String contentDisposition, String mimetype, String referer,
					long contentLength) {
				mWebViewController.onDownloadStart(Tab.this, url, userAgent,
						contentDisposition, mimetype, referer, contentLength);
			}
		};
		mWebBackForwardListClient = new WebBackForwardListClient() {
			@Override
			public void onNewHistoryItem(WebHistoryItem item) {
				if (mClearHistoryUrlPattern != null) {
					boolean match = mClearHistoryUrlPattern.matcher(
							item.getOriginalUrl()).matches();
					if (LOGD_ENABLED) {
						Log.d(LOGTAG, "onNewHistoryItem: match=" + match
								+ "\n\t" + item.getUrl() + "\n\t"
								+ mClearHistoryUrlPattern);
					}
					if (match) {
						if (mMainView != null) {
							mMainView.clearHistory();
						}
					}
					mClearHistoryUrlPattern = null;
				}
			}
		};

		mCaptureWidth = mContext.getResources().getDimensionPixelSize(
				R.dimen.tab_thumbnail_width);
		mCaptureHeight = mContext.getResources().getDimensionPixelSize(
				R.dimen.tab_thumbnail_height);
		updateShouldCaptureThumbnails();
		restoreState(state);
		if (getId() == -1) {
			mId = TabControl.getNextId();
		}
		setWebView(w);
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message m) {
				switch (m.what) {
				case MSG_CAPTURE:
					capture();
					break;
				}
			}
		};
	}

	public boolean shouldUpdateThumbnail() {
		return mUpdateThumbnail;
	}

	/**
	 * This is used to get a new ID when the tab has been preloaded, before it
	 * is displayed and added to TabControl. Preloaded tabs can be created
	 * before restoreInstanceState, leading to overlapping IDs between the
	 * preloaded and restored tabs.
	 */
	public void refreshIdAfterPreload() {
		mId = TabControl.getNextId();
	}

	public void updateShouldCaptureThumbnails() {
		if (mWebViewController.shouldCaptureThumbnails()) {
			synchronized (Tab.this) {
				if (mCapture == null) {
					mCapture = Bitmap.createBitmap(mCaptureWidth,
							mCaptureHeight, Bitmap.Config.RGB_565);
					mCapture.eraseColor(Color.WHITE);
					if (mInForeground) {
						postCapture();
					}
				}
			}
		} else {
			synchronized (Tab.this) {
				mCapture = null;
				deleteThumbnail();
			}
		}
	}

	public void setController(WebViewController ctl) {
		mWebViewController = ctl;
		updateShouldCaptureThumbnails();
	}

	public long getId() {
		return mId;
	}

	void setWebView(WebView w) {
		setWebView(w, true);
	}

	/**
	 * Sets the WebView for this tab, correctly removing the old WebView from
	 * the container view.
	 */
	void setWebView(WebView w, boolean restore) {
		if (mMainView == w) {
			return;
		}
		// If the WebView is changing, the page will be reloaded, so any ongoing
		// Geolocation permission requests are void.
		// DOING_FIXING_geolocation
		// if (mGeolocationPermissionsPrompt != null) {
		// mGeolocationPermissionsPrompt.hide();
		// }
		// DOING_FIXING_permission
		// if (mPermissionsPrompt != null) {
		// mPermissionsPrompt.hide();
		// }

		mWebViewController.onSetWebView(this, w);

		if (mMainView != null) {
			mMainView.setPictureListener(null);
			if (w != null) {
				syncCurrentState(w, null);
			} else {
				mCurrentState = new PageState(mContext, false);
			}
		}
		// set the new one
		mMainView = w;
		// mMainView.setBackgroundColor(0xcc0000);

		// attach the WebViewClient, WebChromeClient and DownloadListener
		if (mMainView != null) {
			
			/*Resources res=mWebViewController.getActivity().getResources();
			Drawable drawable=res.getDrawable(R.drawable.orgne);*/
			mMainView.setWebViewClient(mWebViewClient);
			mMainView.setWebChromeClient(mWebChromeClient);
			mMainView.setBackgroundColor(0);
			mMainView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
			mMainView.addJavascriptInterface(new Object(){
				
				@JavascriptInterface
				public void showSource(String html){
					Log.i("ad_block", html);
				}
				
				@JavascriptInterface
				public void playing(){
//					Log.i("video", "======================= " + src + " === " + currentTime + " ==== " + paused);
//					BrowserJsInject.getInstance().currentTime = currentTime;
//					BrowserJsInject.getInstance().paused = paused;
//					BrowserJsInject.getInstance().isFull = true;
//					loadUrl(src, null);
					fullScreen(true, "", "", "");
				}
				
			}, "local_obj");
			if(mContext!=null){
			screenwidth=Common.getDisplayWidth(mContext);
			}
			//mMainView.setBackground(drawable);
			//mMainView.getBackground().setAlpha(0);
		//	mMainView.setVisibility(View.GONE);
			// Attach DownloadManager so that downloads can start in an active
			// or a non-active window. This can happen when going to a site that
			// does a redirect after a period of time. The user could have
			// switched to another tab while waiting for the download to start.
			mMainView.setDownloadListener(mDownloadListener);
			TabControl tc = mWebViewController.getTabControl();
			if (tc != null && tc.getOnThumbnailUpdatedListener() != null) {
				mMainView.setPictureListener(this);
			}
			if (restore && (mSavedState != null)
					&& !(mCurrentState instanceof HomePageState)) {
				restoreUserAgent();
				WebBackForwardList restoredState = mMainView
						.restoreState(mSavedState);
				if (restoredState == null || restoredState.getSize() == 0) {
					Log.w(LOGTAG, "Failed to restore WebView state!");
					loadUrl(mCurrentState.mOriginalUrl, null);
				}
				mSavedState = null;
			}
		}
	}
	
	void fullScreen(Boolean full, String src, String currentTime, String paused){
		Intent intent = new Intent();
		intent.setAction(StaticConfig.MOXIU_BRWOSER_FULLSCREEN_BROADCAST);
		intent.putExtra("fullScreen", full);
		intent.putExtra("src", src);
		intent.putExtra("currentTime", currentTime);
		intent.putExtra("paused", paused);
		mContext.sendBroadcast(intent);
	}

	/**
	 * Destroy the tab's main WebView and subWindow if any
	 */
	void destroy() {
		if (mMainView != null) {
			dismissSubWindow();
			// save the WebView to call destroy() after detach it from the tab
			WebView webView = mMainView;
			setWebView(null);
			webView.destroy();
		}
	}

	/**
	 * Remove the tab from the parent
	 */
	void removeFromTree() {
		// detach the children
		if (mChildren != null) {
			for (Tab t : mChildren) {
				t.setParent(null);
			}
		}
		// remove itself from the parent list
		if (mParent != null) {
			mParent.mChildren.remove(this);
		}
		deleteThumbnail();
	}

	/**
	 * Create a new subwindow unless a subwindow already exists.
	 * 
	 * @return True if a new subwindow was created. False if one already exists.
	 */
	boolean createSubWindow() {
		if (mSubView == null) {
			mWebViewController.createSubWindow(this);
			mSubView.setWebViewClient(new SubWindowClient(mWebViewClient,
					mWebViewController));
			mSubView.setWebChromeClient(new SubWindowChromeClient(
					mWebChromeClient));
			// Set a different DownloadListener for the mSubView, since it will
			// just need to dismiss the mSubView, rather than close the Tab
			mSubView.setDownloadListener(new BrowserDownloadListener() {
				public void onDownloadStart(String url, String userAgent,
						String contentDisposition, String mimetype,
						String referer, long contentLength) {
					mWebViewController.onDownloadStart(Tab.this, url,
							userAgent, contentDisposition, mimetype, referer,
							contentLength);
					if (mSubView.copyBackForwardList().getSize() == 0) {
						// This subwindow was opened for the sole purpose of
						// downloading a file. Remove it.
						mWebViewController.dismissSubWindow(Tab.this);
					}
				}
			});
			mSubView.setOnCreateContextMenuListener(mWebViewController
					.getActivity());
			return true;
		}
		return false;
	}

	/**
	 * Dismiss the subWindow for the tab.
	 */
	void dismissSubWindow() {
		if (mSubView != null) {
			mWebViewController.endActionMode();
			mSubView.destroy();
			mSubView = null;
			mSubViewContainer = null;
		}
	}

	/**
	 * Set the parent tab of this tab.
	 */
	void setParent(Tab parent) {
		if (parent == this) {
			throw new IllegalStateException("Cannot set parent to self!");
		}
		mParent = parent;
		// This tab may have been freed due to low memory. If that is the case,
		// the parent tab id is already saved. If we are changing that id
		// (most likely due to removing the parent tab) we must update the
		// parent tab id in the saved Bundle.
		if (mSavedState != null) {
			if (parent == null) {
				mSavedState.remove(PARENTTAB);
			} else {
				mSavedState.putLong(PARENTTAB, parent.getId());
			}
		}

		// Sync the WebView useragent with the parent
		if (parent != null
				&& mSettings.hasDesktopUseragent(parent.getWebView()) != mSettings
						.hasDesktopUseragent(getWebView())) {
			mSettings.toggleDesktopUseragent(getWebView());
		}

		if (parent != null && parent.getId() == getId()) {
			throw new IllegalStateException("Parent has same ID as child!");
		}
	}

	/**
	 * If this Tab was created through another Tab, then this method returns
	 * that Tab.
	 * 
	 * @return the Tab parent or null
	 */
	public Tab getParent() {
		return mParent;
	}

	/**
	 * When a Tab is created through the content of another Tab, then we
	 * associate the Tabs.
	 * 
	 * @param child
	 *            the Tab that was created from this Tab
	 */
	void addChildTab(Tab child) {
		if (mChildren == null) {
			mChildren = new Vector<Tab>();
		}
		mChildren.add(child);
		child.setParent(this);
	}

	Vector<Tab> getChildren() {
		return mChildren;
	}

	void resume() {
		if (mMainView != null) {
			setupHwAcceleration(mMainView);
			mMainView.onResume();
			if (mSubView != null) {
				mSubView.onResume();
			}

			restoreHomePageActicleReadPara();
		}
	}

	private void setupHwAcceleration(View web) {
		if (web == null)
			return;
		BrowserSettings settings = BrowserSettings.getInstance();
		if (settings.isHardwareAccelerated()) {
			web.setLayerType(View.LAYER_TYPE_NONE, null);
		} else {
			web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		}
	}

	void pause() {
		if (mMainView != null) {
			mMainView.onPause();
			if (mSubView != null) {
				mSubView.onPause();
			}

			if (mCurrentState != null)
				reportHomePageArticleReadTime();
		}
	}

	void putInForeground() {
		if (mInForeground) {
			return;
		}
		mInForeground = true;
		resume();
		Activity activity = mWebViewController.getActivity();
		mMainView.setOnCreateContextMenuListener(activity);
		if (mSubView != null) {
			mSubView.setOnCreateContextMenuListener(activity);
		}
		// Show the pending error dialog if the queue is not empty
		if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
			// showError(mQueuedErrors.getFirst());
		}
		mWebViewController.bookmarkedStatusHasChanged(this);
	}

	void putInBackground() {
		if (!mInForeground) {
			return;
		}
		capture();
		mInForeground = false;
		pause();
		mMainView.setOnCreateContextMenuListener(null);
		if (mSubView != null) {
			mSubView.setOnCreateContextMenuListener(null);
		}
	}

	boolean inForeground() {
		return mInForeground;
	}

	/**
	 * Return the top window of this tab; either the subwindow if it is not null
	 * or the main window.
	 * 
	 * @return The top window of this tab.
	 */
	WebView getTopWindow() {
		if (mSubView != null) {
			return mSubView;
		}
		return mMainView;
	}

	/**
	 * Return the main window of this tab. Note: if a tab is freed in the
	 * background, this can return null. It is only guaranteed to be non-null
	 * for the current tab.
	 * 
	 * @return The main WebView of this tab.
	 */
	WebView getWebView() {
		return mMainView;
	}

	void setViewContainer(View container) {
		mContainer = container;
	}

	View getViewContainer() {
		return mContainer;
	}

	/**
	 * Return whether private browsing is enabled for the main window of this
	 * tab.
	 * 
	 * @return True if private browsing is enabled.
	 */
	boolean isPrivateBrowsingEnabled() {
		return mCurrentState.mIncognito;
	}

	/**
	 * Return the subwindow of this tab or null if there is no subwindow.
	 * 
	 * @return The subwindow of this tab or null.
	 */
	WebView getSubWebView() {
		return mSubView;
	}

	void setSubWebView(WebView subView) {
		mSubView = subView;
	}

	View getSubViewContainer() {
		return mSubViewContainer;
	}

	void setSubViewContainer(View subViewContainer) {
		mSubViewContainer = subViewContainer;
	}

	/**
	 * @return The geolocation permissions prompt for this tab.
	 */
	// DOING_FIXING_geolocation
	// GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
	// if (mGeolocationPermissionsPrompt == null) {
	// ViewStub stub = (ViewStub) mContainer
	// .findViewById(R.id.geolocation_permissions_prompt);
	// mGeolocationPermissionsPrompt = (GeolocationPermissionsPrompt) stub
	// .inflate();
	// }
	// return mGeolocationPermissionsPrompt;
	// }

	/**
	 * @return The permissions prompt for this tab.
	 */
	// DOING_FIXING_permission
	// PermissionsPrompt getPermissionsPrompt() {
	// if (mPermissionsPrompt == null) {
	// ViewStub stub = (ViewStub) mContainer
	// .findViewById(R.id.permissions_prompt);
	// mPermissionsPrompt = (PermissionsPrompt) stub.inflate();
	// }
	// return mPermissionsPrompt;
	// }

	/**
	 * @return The application id string
	 */
	String getAppId() {
		return mAppId;
	}

	/**
	 * Set the application id string
	 * 
	 * @param id
	 */
	void setAppId(String id) {
		mAppId = id;
	}

	boolean closeOnBack() {
		return mCloseOnBack;
	}

	void setCloseOnBack(boolean close) {
		mCloseOnBack = close;
	}

	String getUrl() {
		return UrlUtils.filteredUrl(mCurrentState.mUrl);
	}

	String getOriginalUrl() {
		if (mCurrentState.mOriginalUrl == null) {
			return getUrl();
		}
		return UrlUtils.filteredUrl(mCurrentState.mOriginalUrl);
	}

	/**
	 * Get the title of this tab.
	 */
	String getTitle() {
		if (mCurrentState.mTitle == null && mInPageLoad) {
			return mContext.getString(R.string.title_bar_loading);
		}
		return mCurrentState.mTitle;
	}

	/**
	 * Get the favicon of this tab.
	 */
	Bitmap getFavicon() {
		if (mCurrentState.mFavicon != null) {
			return mCurrentState.mFavicon;
		}
		return getDefaultFavicon(mContext);
	}

	public boolean isBookmarkedSite() {
		return mCurrentState.mIsBookmarkedSite;
	}

	/**
	 * Return the tab's error console. Creates the console if createIfNEcessary
	 * is true and we haven't already created the console.
	 * 
	 * @param createIfNecessary
	 *            Flag to indicate if the console should be created if it has
	 *            not been already.
	 * @return The tab's error console, or null if one has not been created and
	 *         createIfNecessary is false.
	 */
	// ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
	// if (createIfNecessary && mErrorConsole == null) {
	// mErrorConsole = new ErrorConsoleView(mContext);
	// mErrorConsole.setWebView(mMainView);
	// }
	// return mErrorConsole;
	// }

	/**
	 * Sets the security state, clears the SSL certificate error and informs the
	 * controller.
	 */
	private void setSecurityState(SecurityState securityState) {
		mCurrentState.mSecurityState = securityState;
		mCurrentState.mSslCertificateError = null;
		mWebViewController.onUpdatedSecurityState(this);
	}

	/**
	 * @return The tab's security state.
	 */
	SecurityState getSecurityState() {
		return mCurrentState.mSecurityState;
	}

	/**
	 * Gets the SSL certificate error, if any, for the page's main resource.
	 * This is only non-null when the security state is
	 * SECURITY_STATE_BAD_CERTIFICATE.
	 */
	SslError getSslCertificateError() {
		return mCurrentState.mSslCertificateError;
	}

	int getLoadProgress() {

		if (mInPageLoad) {
			return mPageLoadProgress;
		}
		return 100;
	}

	/**
	 * @return TRUE if onPageStarted is called while onPageFinished is not
	 *         called yet.
	 */
	boolean inPageLoad() {
		return mInPageLoad;
	}

	/**
	 * @return The Bundle with the tab's state if it can be saved, otherwise
	 *         null
	 */
	public Bundle saveState() {
		// If the WebView is null it means we ran low on memory and we already
		// stored the saved state in mSavedState.

		if (mCurrentState == null
				|| InnerJumpToBrowserUtil.APP_ID_FOR_INNER_INCRESS_VALUE
						.equals(mAppId)) {
			return null;
		}
		if (mMainView == null
				|| (isShowingHomePage() && !(BrowserSettings
						.getFactoryResetHomeUrl(mContext)
						.equals(mCurrentState.mUrl)))) {

			// mSavedState = new Bundle();
			// mSavedState.putLong(ID, mId);
			// mSavedState.putString(CURRURL, mCurrentState.mUrl);
			// mSavedState.putString(CURRTITLE, mCurrentState.mTitle);

			return mSavedState;
		}

		if (TextUtils.isEmpty(mCurrentState.mUrl)) {
			return null;
		}

		mSavedState = new Bundle();
		WebBackForwardList savedList = mMainView.saveState(mSavedState);
		if (savedList == null || savedList.getSize() == 0) {
			Log.w(LOGTAG, "Failed to save back/forward list for "
					+ mCurrentState.mUrl);
		}

		mSavedState.putLong(ID, mId);
		mSavedState.putString(CURRURL, mCurrentState.mUrl);
		mSavedState.putString(CURRTITLE, mCurrentState.mTitle);
		mSavedState.putBoolean(INCOGNITO, mMainView.isPrivateBrowsingEnabled());
		if (mAppId != null) {
			mSavedState.putString(APPID, mAppId);
		}
		mSavedState.putBoolean(CLOSEFLAG, mCloseOnBack);
		// Remember the parent tab so the relationship can be restored.
		if (mParent != null) {
			mSavedState.putLong(PARENTTAB, mParent.mId);
		}
		mSavedState.putBoolean(USERAGENT,
				mSettings.hasDesktopUseragent(getWebView()));
		return mSavedState;
	}

	/*
	 * Restore the state of the tab.
	 */
	private void restoreState(Bundle b) {
		mSavedState = b;
		if (mSavedState == null) {
			return;
		}
		// Restore the internal state even if the WebView fails to restore.
		// This will maintain the app id, original url and close-on-exit values.
		mId = b.getLong(ID);
		mAppId = b.getString(APPID);
		mCloseOnBack = b.getBoolean(CLOSEFLAG);
		restoreUserAgent();
		String url = b.getString(CURRURL);
		String title = b.getString(CURRTITLE);
		boolean incognito = b.getBoolean(INCOGNITO);

		if (BrowserSettings.getFactoryResetHomeUrl(mContext).equals(url)) {
			mCurrentState = new HomePageState(mContext, url);
		} else {
			mCurrentState = new PageState(mContext, incognito, url, null);
			mCurrentState.mTitle = title;
		}

		synchronized (Tab.this) {
			if (mCapture != null) {
				DataController.getInstance(mContext).loadThumbnail(this);
			}
		}
	}

	private void restoreUserAgent() {
		if (mMainView == null || mSavedState == null) {
			return;
		}
		if (mSavedState.getBoolean(USERAGENT) != mSettings
				.hasDesktopUseragent(mMainView)) {
			mSettings.toggleDesktopUseragent(mMainView);
		}
	}

	public void updateBookmarkedStatus() {
		mDataController.queryBookmarkStatus(getUrl(), mIsBookmarkCallback);
	}

	private DataController.OnQueryUrlIsBookmark mIsBookmarkCallback = new DataController.OnQueryUrlIsBookmark() {
		@Override
		public void onQueryUrlIsBookmark(String url, boolean isBookmark) {
			try {
				if (mCurrentState.mUrl.equals(url)) {
					mCurrentState.mIsBookmarkedSite = isBookmark;
					mWebViewController.bookmarkedStatusHasChanged(Tab.this);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	public Bitmap getScreenshot() {
		synchronized (Tab.this) {
			return mCapture;
		}
	}

	public boolean isSnapshot() {
		return false;
	}

	private static class SaveCallback implements ValueCallback<Boolean> {
		boolean mResult;

		@Override
		public void onReceiveValue(Boolean value) {
			mResult = value;
			synchronized (this) {
				notifyAll();
			}
		}

	}

	/**
	 * Must be called on the UI thread
	 */
	public ContentValues createSnapshotValues() {
		return null;
	}

	/**
	 * Probably want to call this on a background thread
	 */
	public boolean saveViewState(ContentValues values) {
		return false;
	}

	public byte[] compressBitmap(Bitmap bitmap) {
		if (bitmap == null) {
			return null;
		}
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, stream);
		return stream.toByteArray();
	}

	public void loadUrl(String url, Map<String, String> headers) {
		if (mMainView != null) {
			mMainView.removeJavascriptInterface("MX_NativeCall");
			mPageLoadProgress = INITIAL_PROGRESS;
			mInPageLoad = true;
			if (!mSettings.getHomePage().equals(url)) {

				mCurrentState = new PageState(mContext, false, url, null);
				mWebViewController.onPageStarted(this, mMainView, null);
				if (isShowingHomePage()) {
					hideHomePage();
				}

			} else {
				mCurrentState = new HomePageState(mContext, url);
				mInPageLoad = false;
			}

			if (!mSettings.getHomePage().equals(url)) {
				mMainView.loadUrl(url, headers);
			}
		}
	}

	private String mCurrentHomePageArticleUrl;
	private HomePagePara mCurrentHomePagePara;
    public boolean isShowTitle = true;
	public void loadUrl(String url, Map<String, String> headers,
			String tagFromHome, HomePagePara homePagePara) {
		if (mHasGoneHome) {
			if (mCloseOnBack) {
				mCloseOnBack = false;
			}
		}
		if (mMainView != null) {
			mMainView.removeJavascriptInterface("MX_NativeCall");
			mPageLoadProgress = INITIAL_PROGRESS;
			mInPageLoad = true;
			if (!mSettings.getHomePage().equals(url)) {

				mCurrentState = new PageState(mContext, false, url, null);
				mCurrentState.mHomePagePara = homePagePara;
				mOldState = mCurrentState;
				mWebViewController.onPageStarted(this, mMainView, null);
				if (isShowingHomePage()) {
					hideHomePage();
				}

			} else {
				mCurrentState = new HomePageState(mContext, url);
				mInPageLoad = false;
			}

			if (!mSettings.getHomePage().equals(url)) {
				if (TAG_FROM_HOME_PAGE_GDT.equals(tagFromHome)
						|| (homePagePara != null && TAG_FROM_HOME_PAGE_GDT
								.equals(homePagePara.getTag()))) {
					initParaFromHomePage(url, homePagePara);
					initGDTx();
				}

				if (homePagePara != null
						&& TAG_FROM_SITES_TOUTIAO.equals(homePagePara.getTag())) {

					// 加载广点通
					// mMainView.addJavascriptInterface(
					// new GDTwebviewJavaScriptForToutiao(mMainView),
					// "protocol");
					// initGDT(mContext, 30);
					try {
						if (ads.size() == 0) {
							ads = ((BrowserActivity) mContext).getAds();
							if (ads == null) {
//								Log.d("zhouhua", "初始化失败，加载广点通");
								initH5GDT(mContext, 30);

							}
//							else {
////								Log.d("zhouhua", "++++++++++++++ads++++++++"
////										+ ads.size());
//							}

						}

						toutiao = new GDTwebviewJavaScriptForToutiao(mMainView);
						mMainView.addJavascriptInterface(toutiao, "protocol");

					} catch (Exception e) {

					}

				}
				mMainView.loadUrl(url, headers);
			}
		}
	}

	private GDTwebviewJavaScriptForToutiao toutiao;

	void initParaFromHomePage(String url, HomePagePara homePagePara) {
		this.mCurrentHomePageArticleUrl = url;
		this.mCurrentHomePagePara = homePagePara;
		this.reportReadTime = new ReportReadTime();
	}

	String from = "";

	void initGDTx() {
		try {
			if (mContext instanceof BrowserActivity) {
				BrowserActivity a = (BrowserActivity) mContext;
				from = a.mComeFromTag;
				BDStatistic.postBrowserAdRequest(mContext, from, "0");
				if (from != null && from.length() > 0) {
					if ("from_launcher".equals(from)) {
//						I_POS_ID = B_BrowserMainManager.DETAIL_IPOS_ID;
						AD_PLACE_KEY=AdCons.BROWSER_DETAIL_KEY;
//						AdsUtils.eLog("browser", "from browser");
					} else if ("from-superspeed".equals(from)) {
//						I_POS_ID = MainActivity.DETAIL_I_POS_ID;
						AD_PLACE_KEY=AdCons.SPEEDUP_DETAIL_KEY;
//						AdsUtils.eLog("browser", "from browser");
					} else if ("from-search".equals(from)) {
						AD_PLACE_KEY=AdCons.INTESEARCH_DETAIL_KEY;
//						AdsUtils.eLog("browser", "from browser");
//						I_POS_ID = ConstValue.DETAIL_I_POS_ID;
					}
				}
			} else {
				Log.e("DEBUG", "context is not browser");
			}
			if (!"GT-I9152".equals(android.os.Build.MODEL)) {
				initGDT();
				isShown=false;
				mMainView
						.addJavascriptInterface(
								new GDTwebviewJavaScriptBrowser(mContext,
										mMainView, ad), "MX_NativeCall");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void disableUrlOverridingForLoad() {
		mDisableOverrideUrlLoading = true;
	}

	protected void capture() {

		if (isShowingHomePage()) {
			captureHomePage();
			return;
		}

		if (mMainView == null || mCapture == null)
			return;
		if (mMainView.getContentWidth() <= 0
				|| mMainView.getContentHeight() <= 0) {
			return;
		}
		Canvas c = new Canvas(mCapture);
		final int left = mMainView.getScrollX();
		final int top = mMainView.getScrollY()
				+ mMainView.getVisibleTitleHeight();
		int state = c.save();
		c.translate(-left, -top);
		float scale = mCaptureWidth / (float) mMainView.getWidth();
		c.scale(scale, scale, left, top);
		if (mMainView instanceof BrowserWebView) {
			((BrowserWebView) mMainView).drawContent(c);
		} else {
			mMainView.draw(c);
		}
		c.restoreToCount(state);
		// manually anti-alias the edges for the tilt
		c.drawRect(0, 0, 1, mCapture.getHeight(), sAlphaPaint);
		c.drawRect(mCapture.getWidth() - 1, 0, mCapture.getWidth(),
				mCapture.getHeight(), sAlphaPaint);
		c.drawRect(0, 0, mCapture.getWidth(), 1, sAlphaPaint);
		c.drawRect(0, mCapture.getHeight() - 1, mCapture.getWidth(),
				mCapture.getHeight(), sAlphaPaint);
		c.setBitmap(null);
		mHandler.removeMessages(MSG_CAPTURE);
		persistThumbnail();
		TabControl tc = mWebViewController.getTabControl();
		if (tc != null) {
			OnThumbnailUpdatedListener updateListener = tc
					.getOnThumbnailUpdatedListener();
			if (updateListener != null) {
				updateListener.onThumbnailUpdated(this);
			}
		}
	}

	private void captureHomePage() {
		if (mHomePage == null) {
			return;
		}
		Canvas c = new Canvas(mCapture);
		final int left = mHomePage.getScrollX();
		final int top = mHomePage.getScrollY();
		int state = c.save();
		c.translate(-left, -top);
		float scale = mCaptureWidth / (float) mHomePage.getWidth();
		c.scale(scale, scale, left, top);

		mHomePage.draw(c);

		c.restoreToCount(state);
		// manually anti-alias the edges for the tilt
		c.drawRect(0, 0, 1, mCapture.getHeight(), sAlphaPaint);
		c.drawRect(mCapture.getWidth() - 1, 0, mCapture.getWidth(),
				mCapture.getHeight(), sAlphaPaint);
		c.drawRect(0, 0, mCapture.getWidth(), 1, sAlphaPaint);
		c.drawRect(0, mCapture.getHeight() - 1, mCapture.getWidth(),
				mCapture.getHeight(), sAlphaPaint);
		c.setBitmap(null);
		mHandler.removeMessages(MSG_CAPTURE);
		persistThumbnail();
		TabControl tc = mWebViewController.getTabControl();
		if (tc != null) {
			OnThumbnailUpdatedListener updateListener = tc
					.getOnThumbnailUpdatedListener();
			if (updateListener != null) {
				updateListener.onThumbnailUpdated(this);
			}
		}
	}

	@Override
	public void onNewPicture(WebView view, Picture picture) {
		postCapture();
	}

	private void postCapture() {
		if (!mHandler.hasMessages(MSG_CAPTURE)) {
			mHandler.sendEmptyMessageDelayed(MSG_CAPTURE, CAPTURE_DELAY);
		}
	}

	public boolean canGoBack() {
//		if(mMainView!=null){
//			return mMainView.canGoBack();
//		}else{
//			return false;
//		}
		if (isShowingHomePage()&&!mainManager.isSearchState) {
			return false;
		} else {
			return true;
		}
	}

	public boolean canGoForward() {
		if (isShowingHomePage()) {
			return mHasLoadedPage;
		}
		return mMainView != null ? mMainView.canGoForward() : false;
	}

	public void goBack() {

		if(isShowingHomePage()){
			if(mainManager.isSearchState){
				if(mainManager.searchisFromHome){
					mainManager.showHomePage();
					return;
				}else{
					hideHomePage();
//					Log.e("DEBUG", "BASE UI HIDE HOMEPAGE");
					return;
				}
			}
		}else{
			if(!canGoBack()){
				showHomePage();
//				Log.e("DEBUG", "BASE UI SHOW HOMEPAGE");
				return;
			}
		}
		if (mMainView != null) {
			if (mMainView.canGoBack()) {

				mMainView.goBack();
			} else {
				showHomePage();
				mWebViewController.onPageFinished(this);
			}
			reportHomePageArticleReadTime();
		}
	}

	public void goForward() {
		if (isShowingHomePage()) {
			if (mMainView != null) {
				hideHomePage();
				mWebViewController.onPageFinished(this);

				// restoreHomePageActicleReadPara();

				return;
			}
		}
		if (mMainView != null) {
			// mMainView.setVisibility(View.GONE);
			mMainView.goForward();
			reportHomePageArticleReadTime();
			restoreHomePageActicleReadPara();
		}
	}

	/**
	 * Causes the tab back/forward stack to be cleared once, if the given URL is
	 * the next URL to be added to the stack.
	 *
	 * This is used to ensure that preloaded URLs that are not subsequently seen
	 * by the user do not appear in the back stack.
	 */
	public void clearBackStackWhenItemAdded(Pattern urlPattern) {
		mClearHistoryUrlPattern = urlPattern;
	}

	protected void persistThumbnail() {
		DataController.getInstance(mContext).saveThumbnail(this);
	}

	protected void deleteThumbnail() {
		DataController.getInstance(mContext).deleteThumbnail(this);
	}

	void updateCaptureFromBlob(byte[] blob) {
		synchronized (Tab.this) {
			if (mCapture == null) {
				return;
			}
			ByteBuffer buffer = ByteBuffer.wrap(blob);
			try {
				mCapture.copyPixelsFromBuffer(buffer);
			} catch (RuntimeException rex) {
				Log.e(LOGTAG, "Load capture has mismatched sizes; buffer: "
						+ buffer.capacity() + " blob: " + blob.length
						+ "capture: " + mCapture.getByteCount());
				throw rex;
			}
		}
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder(100);
		builder.append(mId);
		builder.append(") has parent: ");
		if (getParent() != null) {
			builder.append("true[");
			builder.append(getParent().getId());
			builder.append("]");
		} else {
			builder.append("false");
		}
		builder.append(", appid=" + mAppId);
		builder.append(", incog: ");
		builder.append(isPrivateBrowsingEnabled());
		if (!isPrivateBrowsingEnabled()) {
			builder.append(", title: ");
			builder.append(getTitle());
			builder.append(", url: ");
			builder.append(getUrl());
		}
		return builder.toString();
	}

	private void handleProceededAfterSslError(SslError error) {
		if (error.getUrl().equals(mCurrentState.mUrl)) {
			// The security state should currently be SECURITY_STATE_SECURE.
			setSecurityState(SecurityState.SECURITY_STATE_BAD_CERTIFICATE);
			mCurrentState.mSslCertificateError = error;
		} else if (getSecurityState() == SecurityState.SECURITY_STATE_SECURE) {
			// The page's main resource is secure and this error is for a
			// sub-resource.
			setSecurityState(SecurityState.SECURITY_STATE_MIXED);
		}
	}

	public void setAcceptThirdPartyCookies(boolean accept) {
		CookieManager cookieManager = CookieManager.getInstance();
		// TODO �޸ĵĴ���
		/*
		 * if (mMainView != null)
		 * cookieManager.setAcceptThirdPartyCookies(mMainView, accept); if
		 * (mSubView != null) cookieManager.setAcceptThirdPartyCookies(mSubView,
		 * accept);
		 */
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
			try {
				if (mMainView != null)
					cookieManager.setAcceptThirdPartyCookies(mMainView, accept);
				if (mSubView != null)
					cookieManager.setAcceptThirdPartyCookies(mSubView, accept);
			} catch (Exception e) {

			}
		} else {
			if (mMainView != null)
				cookieManager.setAcceptCookie(true);
			if (mSubView != null)
				cookieManager.setAcceptCookie(true);

		}
	}

	private View mHomePage;
	public boolean mHasLoadedPage = false;
	private boolean mShowHomePageFirst = false;

	// private String mLastBackUrl;
	public boolean isShowingHomePage() {
		if (mHomePage != null) {
			return mHomePage.getVisibility() == View.VISIBLE;
		} else {
			return false;
		}
		// return mCurrentState instanceof HomePageState;
	}

	void hideHomePage() {
//		Log.e("DEBUG", "HIDE HOME PAGE");
		if (mHomePage == null) {
			return;
		}
		if (mMainView != null) {
			if (mOldState != null) {
				mCurrentState = mOldState;
			} else {
				mCurrentState = new PageState(mContext, false,
						mMainView.getUrl(), null);
			}

			mCurrentState.mTitle = mMainView.getTitle();

			restoreHomePageActicleReadPara();
			syncCurrentState(mMainView, mMainView.getUrl());
		}
		mWebViewController.onPageFinished(this);
		mHomePage.setVisibility(View.GONE);
		mainManager.showHomePage();
		mWebViewController.onHomePageShowStateChange(this, false);
	}

	void showHomePage() {

		if (mHomePage == null) {
			return;
		}

		// mLastBackUrl = mCurrentState.mUrl;
		if (mMainView != null) {
			reportHomePageArticleReadTime();
		}
		 addressUrl=getUrl();
		mOldState = mCurrentState;
		mCurrentState = new HomePageState(mContext, mSettings.getHomePage());
//		mMainView.loadUrl("javascript:document.getElementsByTagName('video')[0].pause();");
		BrowserJsInject.getInstance().jsInject(mMainView, 0);
		// mCurrentState.mUrl = TabControl.HOME_PAGE_URL;
		mHomePage.setVisibility(View.VISIBLE);
		mWebViewController.onPageFinished(this);
		mPageLoadProgress = 100;
		mainManager.showHomePageFromOtherTab();
		mWebViewController.onProgressChanged(Tab.this);
		mWebViewController.onHomePageShowStateChange(this, true);

	}

	public View getHomePage() {
		return mHomePage;
	}

	public void setHomePage(View homePage) {
		mHomePage = homePage;
	}

	// public void setShowHomePageFirst(boolean showHomePageFirst) {
	// mShowHomePageFirst = showHomePageFirst;
	// }

	public boolean isShowHomePageFirst() {
		if (mHomePage == null) {
			return false;
		}
		return mCurrentState instanceof HomePageState;// mShowHomePageFirst;
	}

	private void refreshBit(int state) {
		BaseUi baseUi = (BaseUi) ((Controller) mWebViewController).getUi();
		if (baseUi != null) {
			TitleBar titlebar = baseUi.getTitleBar();
			if (titlebar != null)
				titlebar.getNavigationBar().refreshBit(state);
		}
	}

//	private String I_POS_ID = "9000808529071142"; // 聚合搜索banner
	// private String I_POS_ID = "9000808529071142"; // 聚合搜索banner
	private static final String MXAPPID = "221632";
	public static AdBaseBean ad;
	private String model=android.os.Build.MODEL;
	
	private String AD_PLACE_KEY=AdCons.BROWSER_DETAIL_KEY;

	public void initGDT() {
		try {
			if (!"GT-I9152".equals(android.os.Build.MODEL)) {
				if (!StaticMethod.iscloseGuangDainByChild(mContext)) {
					initGDTNativeAd();
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initGDTNativeAd() {
		try {
			String placeId=AdConfig.getPositionId(mContext, AD_PLACE_KEY);
			NativeAdFactory factory=new NativeAdFactory(mContext).addAdPlace(placeId, 5, new AdLoadListener() {
				
				@Override
				public void onNoAD(int errorCode, String errorStr) {
					
				}
				
				@Override
				public void onADStatusChanged(AdBaseBean ref) {
					
				}
				
				@Override
				public void onADLoaded(List<AdBaseBean> refs) {
					if (refs != null && refs.size() > 0) {
						if(model.equals(P_modelOne)||model.equals(P_modelTwo)||model.equals(P_modelThree)){
							ad = null;
						}else{
							ad = refs.get(0);
						}
					}
				}
			});
			factory.build();

		} catch (Exception e) {
		}

	}

	private ReportReadTime reportReadTime;

	void reportHomePageArticleReadTime() {

		HomePagePara homePagePara = mCurrentState.mHomePagePara;
		long startReadTime = mCurrentState.mStartLoadTime;
		if (homePagePara == null || reportReadTime == null) {
			return;
		}

		Article article = homePagePara.getArticle();

		if (null != article) {

			long endReadTime = System.currentTimeMillis();
			java.text.DecimalFormat df = new java.text.DecimalFormat("#");
			String difValue = df.format((endReadTime - startReadTime) * 0.001);
			reportReadTime.setParamValue(article);
			reportReadTime.setParamValue(ReportReadTime.PARAM_KEY_READ_TIME,
					difValue);
			reportReadTime.setParamValue(ReportReadTime.PARAM_KEY_EVENT_TIME,
					System.currentTimeMillis());

			try {

				if (((BrowserActivity) mWebViewController.getActivity())
						.getFromTag().equals("from-search")) {
					reportReadTime.setParamValue(
							ReportListPageTime.PARAM_KEY_SOURCE,
							"MX_INTEGRATE_SEARCH");
				} else if (((BrowserActivity) mWebViewController.getActivity())
						.getFromTag().equals("from-superspeed")) {
					reportReadTime.setParamValue(
							ReportListPageTime.PARAM_KEY_SOURCE, "mx_kapian");
				} else {
					reportReadTime.setParamValue(
							ReportListPageTime.PARAM_KEY_SOURCE, "mx_browser");
				}
			} catch (Exception e) {
				reportReadTime.setParamValue(
						ReportListPageTime.PARAM_KEY_SOURCE, "mx_browser");
			}
			
			if (mContext != null)
				NewsSdkReportImpl.getInstance(mContext).report(reportReadTime);
		}
	}

	void restoreHomePageActicleReadPara() {
		if (mCurrentState.mHomePagePara != null) {
			mCurrentState.mStartLoadTime = System.currentTimeMillis();
		}

	}

	public boolean isAppTab() {
		return !TextUtils.isEmpty(mAppId);
	}

	private boolean mHasGoneHome = false;

	public void setHasGoneHomePage(boolean hasGoneHome) {
		mHasGoneHome = hasGoneHome;
	}

	public boolean getHasGoneHomePage() {
		return mHasGoneHome;
	}

	/* 夜间模式 */
	public void OpenNight(Boolean isN) {
		if (isN) {
			if (mMainView != null) {
				mMainView.loadUrl(localStringBuilder.toString());
			}
			isNight = true;
		} else {
			isNight = false;
			if (mMainView != null) {
	mMainView.loadUrl("javascript:if(typeof __lb_night_call !== 'undefined'){__lb_night_call(\"switch_day\");}");
			}
		}
	}

	public static void readToBuffer(StringBuffer buffer, String filePath)
			throws IOException {
		InputStream is = new FileInputStream(filePath);
		String line; // 用来保存每行读取的内容
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		line = reader.readLine(); // 读取第一行
		while (line != null) { // 如果 line 为空说明读完了
			buffer.append(line); // 将读到的内容添加到 buffer 中
			buffer.append("\n"); // 添加换行符
			line = reader.readLine(); // 读取下一行
		}
		reader.close();
		is.close();
	}

	public static String readFile(String filePath) throws IOException {
		StringBuffer sb = new StringBuffer();
		readToBuffer(sb, filePath);
		return sb.toString();
	}

	private boolean isShown = false;

	@Override
	public void onShow() {
		if (!isShown) {
			if (ad != null && mMainView != null) {
				ad.onExposured(mMainView);
				BDStatistic.postBrowserAdShow(mContext,
						BDStatistic.BROWSER_NEWS_DETAIL_SLOT, from,
						ad.getReportName(), ad.getReportRefer());
				isShown = true;

			}
		}
	}

	public List<NativeADDataRef> ads = new ArrayList<NativeADDataRef>();
	private NativeAD gdtnativead2;

	public void initH5GDT(Context mContext, int count) {
		try {
			if (!"GT-I9152".equals(android.os.Build.MODEL)) {
				if (!StaticMethod.iscloseGuangDainByChild(mContext)) {
					initGDTNativeAd2();
					loadAd2(count);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String I_POS_ID_2 = "3000207764796345";

	public void initGDTNativeAd2() {

		try {
			MultiProcessFlag.setMultiProcess(true);
			gdtnativead2 = new NativeAD(mContext, MXAPPID, I_POS_ID_2,
					new NativeAdListener() {

						@Override
						public void onADLoaded(List<NativeADDataRef> refs) {

							if (refs != null && refs.size() > 0) {
								for (NativeADDataRef nativeADDataRef : refs) {
									if (nativeADDataRef.isAPP()) {
										ads.add(nativeADDataRef);
										continue;
									}
								}
							}

						}

						@Override
						public void onNoAD(int errorCode) {
						}

						@Override
						public void onADStatusChanged(NativeADDataRef ref) {

						}
					});

		} catch (Exception e) {
		}
	}

	protected void loadAd2(int count) {
		if (count >= 30) {
			count = 30;
		}
		// 一次拉取的广告条数：范围1-30
		try {

			gdtnativead2.loadAD(count);

		} catch (Exception e) {
		}
	}
	private List<NativeADDataRef> mDataRefs;
	public class GDTwebviewJavaScriptForToutiao {
		private WebView view;
		
		private NativeADDataRef adDataRef;

		public GDTwebviewJavaScriptForToutiao(WebView view) {
			this.view = view;
			

		}

		@JavascriptInterface
		public JSONObject requestInjectedAd(final int count) {
			try {
				List<NativeADDataRef> useDataRefs = new ArrayList<NativeADDataRef>();
				mDataRefs = new ArrayList<NativeADDataRef>();
				if(ads.size()< 4){
					initH5GDT(mContext, 20);
				}
				if (ads != null && ads.size() > 0) {
					for (int i = 0; i < count; i++) {
						NativeADDataRef adDataRef = ads.get(i);
						mDataRefs.add(adDataRef);
						useDataRefs.add(adDataRef);
					}

					if (ads.size() <= count) {
						initH5GDT(mContext, 30);
					}
					JSONObject object = new JSONObject();
					try {
						JSONArray array = new JSONArray();

						for (int i = 0; i < count; i++) {
							NativeADDataRef nativeADDataRef = useDataRefs
									.get(i);
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("IconUrl",
									nativeADDataRef.getIconUrl());
							jsonObject.put("title", nativeADDataRef.getTitle());
							jsonObject.put("coverUrl",
									nativeADDataRef.getImgUrl());
							jsonObject.put("body", nativeADDataRef.getDesc());
							array.put(i, jsonObject);
						}
						object.put("ads", array);

					} catch (JSONException e) {
						e.printStackTrace();
					}
					ads.removeAll(useDataRefs);
					return object;
				} else {
					return null;
				}
			} catch (Exception e) {
				return null;
			}

		}

		@JavascriptInterface
		public void clickInjectedAd(int index) {

			try {
				if (mDataRefs == null) {
					return;
				}
				NativeADDataRef nativeADDataRef = mDataRefs.get(index);
				nativeADDataRef.onExposured(view);
				nativeADDataRef.onClicked(view);


			} catch (Exception e) {
			}
		}

		@JavascriptInterface
		public JSONObject requestDetailAd() {
			try {

				JSONObject object = new JSONObject();
				if (ads != null && ads.size() > 0) {

					adDataRef = ads.get(new Random().nextInt(ads.size()));
					try {
						object.put("IconUrl", adDataRef.getIconUrl());
						object.put("title", adDataRef.getTitle());
						object.put("coverUrl", adDataRef.getImgUrl());
						object.put("body", adDataRef.getDesc());
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					initH5GDT(mContext, 30);
				}
				return object;

			} catch (Exception e) {
				return null;
			}
		}

		@JavascriptInterface
		public void clickDetailAd() {
			try {

				if (adDataRef == null) {
					return;
				}
				adDataRef.onExposured(view);
				adDataRef.onClicked(view);
			} catch (Exception e) {
			}
		}

	}

}
